Factorization algorithm in C

Asked

Viewed 55 times

2

When creating a number factor algorithm with while I see that by input of the number 21 onwards, the result is wrong -negative.

#include <stdio.h>

long int i=1, ii=1, num, fat=1, somatorio;

int main (){

  while(i <=  5){
    printf("Insira um número: ");
    scanf("%ld", &num);

    ii = 1;
    fat = 1;
    
    while(ii <= num){
      fat = fat * ii;
      ii++;
    }

    printf("Fatorial: %ld\n",fat);

    somatorio = fat + somatorio; 

    i++;

  }
    printf("\nSomatório dos fatoriais: %ld\n\n", somatorio);
}

The program should read 5 numbers and at the end present the sum of factorial.

1 answer

2


The negative value that is returning from the factorial is because the variables are being declared as type "long int" which has an interval of (-2.147.483.648 to 2.147.483.647), in which case to circumvent the error uses the long int unsigned data type which has the longest interval

Follow the corrected code:

#include <stdio.h>

unsigned long long int i=1, ii=1, num, fat=1, somatorio;

int main (){

while(i <=  5){
    printf("Insira um número: ");
    scanf("%ld", &num);

    ii = 1;
    fat = 1;

    while(ii <= num){
      fat = fat * ii;
      ii++;
    }

    printf("Fatorial: %llu\n",fat);

    somatorio = fat + somatorio;

    i++;

}
    printf("\nSomatório dos fatoriais: %llu\n\n", somatorio);
}

The factorial number limit is 20! after that number exceeds the 64 bits proposed by the long int unsigned data type.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.