Skip to content

Instantly share code, notes, and snippets.

@rohithpeddi
Created December 21, 2016 11:59
Show Gist options
  • Save rohithpeddi/df7c055879bf4da14b271e18ef28cda3 to your computer and use it in GitHub Desktop.
Save rohithpeddi/df7c055879bf4da14b271e18ef28cda3 to your computer and use it in GitHub Desktop.
Matrix exponentiation used in many areas - For finding recurrences, fibonocci sum, etc
/*
Can be used for bigger powers but be careful of long value overflow
current[][] - is the initial state of the matrix used
result[][] - is the final matrix after exponentiation
power - in the argument tells the exponent of the matrix
choose mod accordingly !
*/
public class MatrixExponentiation{
public static long[][] mult(long[][] A,long[][] B){
long[][] C = new long[3][3];
for(int i = 0; i <3; i++){
for(int j = 0; j < 3; j++) {
long tmp=0L;
for(int k = 0; k < 3; k++) {
tmp += A[i][k]*B[k][j];
}
C[i][j]= tmp%mod;
}
}
return C;
}
public static long[][] getM(long power){
long[][] result = {{1,0,0},{0,1,0},{0,0,1}};
long[][] current = {{0,0,3},{1,0,2},{0,1,1}};
while(power>0){
if(power%2==1){
result = mult(result,current);
}
current = mult(current,current);
power = power/2;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment