Not if you want to detect overflow.
Code:
#include <stdio.h>
typedef enum { FALSE, TRUE } Boolean;
Boolean calcFactorial (int n, int* nfact)
{
*nfact = 1;
while(n > 0)
{
*nfact = *nfact * n;
n--;
}
if(*nfact < 0x7fffffff)
{
return TRUE;
}
else
{
return FALSE;
}
}
int main()
{
int value, result;
for ( value = 0; value < 20; ++value )
{
if ( calcFactorial(value,&result) )
{
printf("%2d! = %d\n", value, result);
}
}
return 0;
}
/* my output
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 1932053504
14! = 1278945280
15! = 2004310016
16! = 2004189184
17! = -288522240
18! = -898433024
19! = 109641728
*/
[edit]An expected output would be:
Code:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600