Last Digit of a Large Fibonacci Number fast algorithm

微笑、不失礼 提交于 2020-03-03 01:43:48

问题


I'm trying to solve Fibonacci using java, but my code takes so long with big numbers.

Problem Description Task. Given an integer 𝑛, find the last digit of the 𝑛th Fibonacci number 𝐹𝑛 (that is, 𝐹𝑛 mod 10).

Input Format. The input consists of a single integer 𝑛.

Constraints. 0 ≤ 𝑛 ≤ 10⁷.

Output Format. Output the last digit of 𝐹𝑛.

My code:

public class FibonacciLastDigit {

private static int getFibonacciLastDigitNaive(int n) {
    if (n <= 1) {
        return n;
    }
    BigInteger first = BigInteger.ZERO;
    BigInteger second = BigInteger.ONE;
    BigInteger temp;

    for (int i = 1; i < n; i++) {
        temp = first.add(second);
        first = second;
        second = temp;
    }
    return second.mod(BigInteger.TEN).intValue();
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    System.out.println(getFibonacciLastDigitNaive(n));
}}

My code fails if input = 613455 it takes 30 seconds to get value and max allowed time is 1.5 second.

I had to use big Integer because long isn't enough.


回答1:


Your implementation is indeed naive, because you're asked to get the last digit of the Fibonacci number not the actual Fibonacci number itself. You only need to keep the track of the last digit, other digits don't matter.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    System.out.println(getFibonacciLastDigit(n));
}

private static int getFibonacciLastDigit(int n) {
    if (n <= 1) {
        return n;
    }
    int first = 0;
    int second = 1;
    int temp;

    for (int i = 1; i < n; i++) {
        temp = (first + second) % 10;
        first = second;
        second = temp;
    }
    return second;
}



回答2:


There is a cycle in the last digit of the Fibonacci numbers. It repeats for every 60 numbers. So just build a table of the last digit of the first 60 numbers, then do a modulo 60 operation on the input and a table lookup.

You may see the cycle in any online (or offline) table of Fibonacci numbers. One link at the bottom.

For building the table, for each calculated number you may subtract 10 if it’s over 9 since you only need the last digit, and the last digit of each number only depends on the last digit of the two previous numbers. You can use int math (you neither need long nor BigInteger).

Link: The first 300 Fibonacci numbers, factored



来源:https://stackoverflow.com/questions/54480322/last-digit-of-a-large-fibonacci-number-fast-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!