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.