Skip to content

Instantly share code, notes, and snippets.

@Bahaaib
Last active January 15, 2019 16:06
Show Gist options
  • Select an option

  • Save Bahaaib/8f0ecabe9cf06c7d9e3c73f8943bcbd7 to your computer and use it in GitHub Desktop.

Select an option

Save Bahaaib/8f0ecabe9cf06c7d9e3c73f8943bcbd7 to your computer and use it in GitHub Desktop.
Calculating Fibonacci numbers for very large N using Matrices Multiplication Algorithm
import java.math.BigInteger;
import java.util.Scanner;
public class Fibonacci {
static double num;
static Runtime runtime = Runtime.getRuntime();
static long maxMem, allocMem;
static long startTime, endTime;
public static void main(String[] args) {
maxMem = runtime.maxMemory()/(1024*1024);
allocMem = runtime.totalMemory()/(1024*1024);
Scanner input = new Scanner(System.in);
int n = input.nextInt();
startTime = System.nanoTime();
System.out.println(effFib(n).mod(BigInteger.TEN));
endTime = System.nanoTime();
//System.out.println((endTime - startTime) / 1000000 + " Millisecond");
}
private static BigInteger effFib(int n) {
BigInteger[] matrix = {BigInteger.ONE, BigInteger.ONE, BigInteger.ONE, BigInteger.ZERO};
return matrixPow(matrix, n)[1];
}
private static BigInteger[] matrixPow(BigInteger[] matrix, int n){
BigInteger[] result = {BigInteger.ONE, BigInteger.ZERO, BigInteger.ZERO, BigInteger.ONE};
while (n != 0){
if (n % 2 != 0)
result = matrixMultiply(result, matrix);
n /= 2;
matrix = matrixMultiply(matrix, matrix);
}
return result;
}
private static BigInteger[] matrixMultiply(BigInteger[] x, BigInteger[] y){
return new BigInteger[]{
multiply(x[0], y[0]).add(multiply(x[1], y[2])),
multiply(x[0], y[1]).add(multiply(x[1], y[3])),
multiply(x[2], y[0]).add(multiply(x[3], y[2])),
multiply(x[2], y[1]).add(multiply(x[3], y[3]))
};
}
private static BigInteger multiply(BigInteger x, BigInteger y){
return x.multiply(y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment