/* * Program to compute factorial using recursion, * with check for overflow. * * (Exits the program on overflow -- not good in a larger * program but okay for purposes of illustration.) */ #include #include /* has INT_MAX */ #include /* has exit() */ int factorial(int n); int main(void) { int n; printf("enter n\n"); if (scanf("%d", &n) != 1) { printf("not number\n"); return 1; } if (n < 0) { printf("negative\n"); return 1; } printf("factorial(%d) is %d\n", n, factorial(n)); return 0; } int factorial(int n) { if (n <= 0) return 1; else { /* can't test n * factorial(n-1) > INT_MAX directly */ if (factorial(n-1) > (INT_MAX / n)) { printf("overflow!\n"); exit(1); } return n * factorial(n-1); } }