Algorithm for finding last 5 digits of Fibonacci number

Nikita Voronin :

I'm trying to implement an iterative algorithm for computing the last 5 digits of the Nth Fibonacci number. I have no issue finding the nth Fibonacci number itself and displaying only the last 5 digits, however, my assignment also asks to find the maximum n for which my program runs under 1 minute. The problem is, the N gets very huge, and therefore Fibonacci numbers are huge as well. Should I just use BigInteger to store values and in the end use % operator to display 5 last digits? Is there a way to use the fact that I only need last 5 digits to speed up the process? I feel like I'm missing the point of the assignment.

Assignment says this: Using Java, implement the iterative algorithm for computing the last 5 digits of the nth Fibonacci number. Perform an experiment to find the largest value of n for which your program runs under 1 minute on your computer.

My code for finding last 5 digits of Nth Fibonacci number:

public static int Fibonacci(int n){
    int a, b = 0, c = 1;
    for(int i = 1; i < n; i++){
        a = b;
        b = c;
        c = a + b;
    }
    return c % 100000;
}

I would also love to know if there are better iterative solutions.

Ardavel :

As you already noticed, finding the last 5 digits is equivalent to calculating the result modulo 100000. To solve the overflow issue, you can apply the % 100000 operation to the intermediate results so no BigInteger is required. It would be: c = (a + b) % 100000.

In theory, you can improve the time complexity of the solution from O(N) to O(log(N)). The algorithm is based on fast matrix exponentiation. However, your assignment requires the iterative approach so I mention it just for completeness.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=418372&siteId=1