Tom Benny
Tom Benny

Reputation: 73

factorial int value in C

so i've been recently doing a homeschool project in C. We were asked to make code which returns you the factorial of the number you put in. That's cool and simple, but we were also asked to make something, what will write you an error, if the number of factorial is higher value than the max value of integer.

int main() {
int a, i;
int faktorial = 1;
a = 10;


if (a < 0)
    printf("Chyba, faktorial z nekladneho cisla neexistuje. \n");
else {
    for (i = 1; i <= a; ++i) {
        faktorial *= i;
    }
    printf("Faktorial z %d = %d\n", a, faktorial);

}

return 0;

}

That's my code, which works perfectly, unless the value of factorial is bigger than the value of int. I've tried to make if statement, like if (faktorial > 2147483647) than printf error message, but it just didnt work and it still makes faktorial = 0.

Upvotes: 5

Views: 499

Answers (1)

S.S. Anne
S.S. Anne

Reputation: 15586

You can't test if a factorial is greater than INT_MAX with > because an int will never be greater than INT_MAX. Instead, you can divide INT_MAX by a beforehand, and check if faktorial is ever greater than that. This is so you don't have to divide on every iteration:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/* ... */
    int bound = INT_MAX / a;
    for (i = 1; i <= a; ++i) {
        if(faktorial > bound)
        {
            fputs("Integer Overflow!\n", stderr);
            return EXIT_FAILURE;
        }
        faktorial *= i;
    }

Assuming a is strictly positive, this will always work.

Upvotes: 5

Related Questions