Java – Factorial of cache using static int arrays

Factorial of cache using static int arrays… here is a solution to the problem.

Factorial of cache using static int arrays

static int count = 0;
static long[] cache = new long[3000];

static {
    cache[0] = 1;
}
public static void main(String args[]) {
    for (int i = 0; i < 100; i++){
        factorial_with_cache(2999);
    }
    System.out.println(count);        
}

public static long factorial_with_cache (int n){
    if (cache[n] != 0){
        return cache[n];
    }
    cache[n] = n * factorial_with_cache(n - 1);
    count++;
    return cache[n];
}

I built a function that calculates factorials using caching (ignoring overflows).

But its runtime isn’t much better compared to the non-caching feature, and I found caching not working.

Because I expected the variable “count” to be 2999 after the loop, but I found that it was 293465 and much more than that. (There is no loop, it prints 2999).

What’s wrong with this function?

Solution

Because the range of the long data type:

long 8 bytes (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)

Before you search for the factorial of 25, your factorial gives a positive value.
After 25, the calculated factorial value is negative (which means you overflow for a long time) and your count will work as expected until 65 factorial is calculated (until negative) and then the value of factorial 66 reaches 0…

Just print the factorial below:

for (int i = 0; i < 100; i++) {
          long fact=factorial_with_cache(66);
          System.out.println(fact);
        }
        System.out.println(count);

The count is printed as

(forLoopCount*(number-65))+65 , In your case (100*(2999-65))+65 is 293465

Because the factorial value traced back in the cache is not zero, it is the 65th element (at index 64).

Related Problems and Solutions