Originally posted by Chook
Im about writing a program input number, implemented it with apply this formular: n!/(n/2)!, using recursive function. Question is: How would I be able to find the largest number of n without overflowing, which number is too big for the computer handle?
An example using limits.h and an integral type might be as follows.
Code:
#include <stdio.h>
#include <limits.h>
int main(void)
{
unsigned long n;
for ( n = 2UL; n < 200UL; n += 2UL )
{
/* calculate n!/(n/2)! */
unsigned long i, result = n, n2 = n / 2UL;
for ( i = n - 1; i > n2; --i )
{
/* check for possible overflow before multiplying */
if ( result > ULONG_MAX / i )
{
printf("overflow warning: %lu * %lu would exceed %lu\n",
result, i, ULONG_MAX);
return 0;
}
/* multiply will not overflow */
result *= i;
}
printf("%lu!/%lu! = %lu\n", n, n2, result);
}
return 0;
}
/* my output
2!/1! = 2
4!/2! = 12
6!/3! = 120
8!/4! = 1680
10!/5! = 30240
12!/6! = 665280
14!/7! = 17297280
16!/8! = 518918400
overflow warning: 1764322560 * 10 would exceed 4294967295
*/
A similar approach could be used with floating point; DBL_MAX and friends are found in float.h.