Factorial case 13 and 16

Joined
Jun 14, 2021
Messages
5
Reaction score
0
My factorial program does not give me the correct results in cases, for instance 13 should be 6227020800 and my output is 1932053504. I display my C program below, is someone able to help me fix it for these cases? I know the formula for factorial is n × (n - 1).

C:
int    factorial(int nb)
{
    int    res;
    int i;

    res = 1;
    i = 1;
    if (nb == 0 || nb == 1)
        return (1);
    while (++i <= nb)
    {
        res *= i;
    }
    return (res);
}
 
Last edited:
Joined
Mar 28, 2022
Messages
82
Reaction score
11
The problem is you're overflowing the maximum value an int can hold. Use a storage variable that can hold a larger quantity, such as double.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top