0

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));
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
kha
  • 9
  • 1
  • If you compiled with warnings enabled with `-Wall` the bad `printf` mentioned by John would be flagged at compile time – Craig Estey Aug 07 '22 at 00:54
  • 3
    The C standard allows a `long` to be 32-bits. So it's entirely possible that your code will only work up to 12 even after fixing the format string. If you want to use 64-bit numbers, use `long long` or `uint64_t`. But even with 64 bits it'll only work up to 20. – user3386109 Aug 07 '22 at 01:10

2 Answers2

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

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

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)

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278