Home > Enterprise >  Factorial giving wrong answers for numbers bigger than 12
Factorial giving wrong answers for numbers bigger than 12

Time:08-08

The user enters a number which will get passed to the calcFactorial function. As long as the number is bigger than zero the loop will repeat. The number will be multiplied by whatever is stored in result. One will be subtracted from x each time the loop is repeated.

When I tested it the program only worked up to 12. After that I would be given the wrong number. Are the numbers too large? I'm not sure what the issue is.

#include <stdio.h>

long calcFactorial(int x){
    long result = 1;
    while(x > 0){
        result *= x;
        x--;
    }
    return result;
}
int main(){
    int x;
    printf("Enter a number: ");
    scanf(" %d",&x);
    printf("%d",calcFactorial(x));
}

CodePudding user response:

printf("%d",calcFactorial(x));

calcFactorial returns a long, so the format specifier to print it should be %ld rather than %d.

CodePudding user response:

Factorial values grow quickly and quickly exceed the range that can be stored in built-in integer types. If you try to create a factorial larger than 12 using a 32-bit integer type, the results are unreliable (signed integer overflow leads to undefined behaviour; unsigned integer overflow means the result is accurate modulo 232).

  • A 32-bit integer can store factorials up to 12!

  • A 64-bit integer can store factorials up to 20!

  • A 128-bit (unsigned) integer can store factorials up to 34!

  • A 256-bit integer can store factorials up to 57!

  • A 512-bit (unsigned) integer can store factorials up to 98!

  • Using IEEE 754 64-bit floating-point arithmetic, you can store approximations up to 170! (7.257415615307994E 306)

  • Using IEEE 754 128-bit floating-point arithmetic, you can store approximations up to 1754! (1.979261890105010E 4930)

You probably don't have a compiler that handles sizes bigger than 64-bit integers (though GCC has rudimentary support for 128-bit integers).

See also Calculating factorial of large numbers in C.

There is code to calculate factorials for the bc command available in my SOQ repository on GitHub as file factorial.bc in the src/miscellany sub-directory.

  • Related