Skip to content

Instantly share code, notes, and snippets.

@sreeprasad
Last active January 12, 2018 04:19
Show Gist options
  • Save sreeprasad/01830fec5abcc113583d2939586ed9fc to your computer and use it in GitHub Desktop.
Save sreeprasad/01830fec5abcc113583d2939586ed9fc to your computer and use it in GitHub Desktop.
last digit of sum of first N Fibonacci number
/**
* Get the last digit of the nth fibonocci number.
*/
private static long getFibonacciSumNaive(long n) {
if (n <= 1)
return n;
// we are using array length = 60 because
// fib[i] % 10 has a pissano period of 10
// i.e fib[i]%10 repeats itself after every 60 times.
int [] array = new int[60];
array[0]=0;
array[1]=1;
//fib[n-1] = fib[n+1] - fib[n]
//fib[n-2] = fib[n] - fib[n-3]
//fib[n-3] = fib[n-3] - fib[n-4]
// .. = .. - ..
// .. = .. - ..
//fib[0] = fib[2] - fib[1]
//-------------------------------
// LHS = fib[0] + fib[1] + .... fib[n-2] + fib[n-1] = Sn[n-1]
// RHS = fib[n+1] - fib[1] = fib[n+1] - 1
// Sn[n-1] = fib[n+1]-1
// Therefore Sn[n] = fib[n+2] - 1
// first populate all the modulo remaininder up to pisano number 60
for(int i=2;i<60;i++){
array[i] = (array[i-1]+array[i-2])%60;
}
// get index of fib[n+2]%60
int index= (int)((n+2)%60);
// array[index] = fib[n+2]
// Sn[n] = array[index]-1 = fib[n+2]-1
int val = array[index]-1;
// finally get the last digit of Sn[n]
return val%10;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment