PDA

View Full Version : Need Programming Homework Help Now!

hapoo
10-25-2001, 06:03 PM
ok guys... simple program but i dont have time. I just need a program writen in C that calculates the factorial of a number!

kinda like this

main()
{
int num;
scanf("%d", &num);
factorial(num);
printf("%d", num);
}

int factorial(int num)
{
int total;
if(num = 1){return 1;}
total = num*factorial(num-1);
}

The program is due tonight, any and all help is greatly appreciated! Thanks in advance.

Markel
10-25-2001, 06:09 PM
Although factorial calculation is the classic example used for recursion, it is actually a very poor implementation due to the calculation intensity once numbers get very large. Most efficient implementations use a lookup table for smaller numbers (the last time I remember this was like up to 27 or something, but that was a few years ago), and then use a logarithmic function to estimate values that are above this (since the number of significant digits that can be used can be returned by such a function).

However, as long as you have a properly recursive compiler, your example looks like it should work.

hapoo
10-25-2001, 06:11 PM
The program MUST be recursively excecuted and it MUST check for overflow... which btw happens after 13 factorial on a 32 bit computer.
the one i just wrote returns 1 for any number... and doesn't check for overflow.

Markel
10-25-2001, 06:12 PM
One note - if you can use a long instead of an int, you won't overflow as quickly.

hapoo
10-25-2001, 06:13 PM
Originally posted by Markel
One note - if you can use a long instead of an int, you won't overflow as quickly.

must use integer. Just following instructions on the lab, not making this stuff up :)

Markel
10-25-2001, 06:16 PM
Can you just put a check in factorial for num > 13 (print error and return 0 or something)?

hapoo
10-25-2001, 06:22 PM
Originally posted by Markel
Can you just put a check in factorial for num > 13 (print error and return 0 or something)?