LearnFrenzy
Sign in Take a free test

C Variables · Variable Programs · Question 6

Factorial with a static cache array in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links