Compute factorials up to 20, caching results in a static array so each value is calculated only once.
Solution
main.c
#include <stdio.h>
unsigned long long fact(int n) {
static unsigned long long cache[21] = {1}; /* cache[0] = 0! = 1; the rest start at 0 */
static int computed = 0; /* highest n stored so far */
while (computed < n) {
computed++;
cache[computed] = cache[computed - 1] * computed;
}
return cache[n];
}
int main(void) {
printf("%llu %llu %llu\n", fact(5), fact(10), fact(20));
return 0;
}
Output Verified by compiling and running
120 3628800 2432902008176640000
The static array keeps every factorial already computed; later calls only extend it. 20! is the largest factorial that fits in 64 bits, hence the size 21.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!