CodexBloom - Programming Q&A Platform

best practices for Integer Overflow When Calculating Factorials in C?

πŸ‘€ Views: 15 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
c factorial integer-overflow big-integers C

I'm working on a C program to calculate factorials using a simple iterative approach. However, I've noticed that the program gives incorrect results for values above 12, and I suspect that this is due to integer overflow. I'm using `unsigned long long` to store the results, but I still get incorrect results when calculating factorials for numbers greater than 20. Here’s the code I have so far: ```c #include <stdio.h> unsigned long long factorial(int n) { unsigned long long result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; } int main() { int number = 20; printf("Factorial of %d is %llu\n", number, factorial(number)); return 0; } ``` When I run this code with `number = 20`, it works fine, but if I try `number = 21`, I get the output as `51090942171709440000` instead of `51090942171709440000`. It seems correct, but I have read that this exceeds the range of `unsigned long long`. I tried using a larger data type like `__uint128_t`, but my compiler (GCC 9.3.0) doesn't support it directly. What would be the best approach to handle larger factorial calculations without running into overflow issues? Should I switch to a library for big integers or implement my own? Also, is there a more efficient way to compute large factorials without manual checks? Any guidance would be appreciated!