0

I just learned of integer overflow but I need help fixing it

int factorial()
{
    int answer = 1;
    int n;
    int factNum; 
    printf("Please enter a postive integer:\n");
    // user input is stored in factNum
    scanf("%i", &factNum); 

    for(n =1; n <= factNum;n++)
    {
        answer = answer * n;
    }
    return answer;
}
user1829
  • 33
  • 1
  • 6
  • This is because 13! = 6,227,020,800, which is larger than the largest value an unsigned 32 bit integer can hold. Even if you are able to use unsigned 64 bit ints, the largest value you could have is 21!. So I guess the question is what do you want your program to do / how do you want to use the factorial – Zen Monkey Feb 17 '20 at 02:31
  • The program is just suppose to return the factorial of the input – user1829 Feb 17 '20 at 02:40
  • Factorials up to 12! fit into a 32-bit integer. Factorials up to 20! fit into a 64-bit integer. After that, you've run out of bits on most machines. However, 34! fits into an unsigned 128-bit integer, 57! fits into a 256-bit integer, and 98! fits into an unsigned 512-bit integer. – Jonathan Leffler Feb 17 '20 at 03:42

1 Answers1

0

An int can only store numbers up to 2^31 - 1 (though technically this is implementation defined). If you want numbers up to 2^64 (roughly 21!), change your int answer = 1; to unsigned long long answer = 1;.

If you want more than that, you'll have to use some sort of struct or array of numbers to keep track of numbers with more than 64 bits. You can write your own (which may be tricky) or use an existing library such as https://en.wikipedia.org/wiki/GNU_Multiple_Precision_Arithmetic_Library

James McDowell
  • 2,668
  • 1
  • 14
  • 27