AcWing 1303. 斐波那契前 n 项和(Java)
原题链接
中等
作者:
上杉
,
2021-04-16 11:25:05
,
所有人可见
,
阅读 296
java 矩阵快速幂
import java.util.*;
public class Main{
static int m ;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int n = input.nextInt();
m = input.nextInt();
//1 1 2 3
long[][] matrix = cal(n-1);
// for(int i = 0 ; i < 3 ; i++){
// System.out.println(Arrays.toString(matrix[i]));
// }
long res = 0;
for(int i = 0 ; i < 3 ; i++){
res = (res + matrix[i][2]) % m;
}
System.out.println(res);
}
public static long[][] cal(int n ){
long[][] base = {{0,1,0},{1,1,1},{0,0,1}};
long[][] res = {{1,0,0},{0,1,0},{0,0,1}};
while(n > 0){
if((n & 1) == 1){
res = multi(res,base);
}
n = n >> 1;
base = multi(base,base);
}
return res;
}
public static long[][] multi(long[][] A,long[][] B){
long[][] res = new long[A.length][B[0].length];
for(int i = 0 ; i < A.length ; i++){
for(int j = 0 ; j < B[0].length ; j++){
for(int k = 0 ; k < A[0].length ; k++){
res[i][j] = (res[i][j] + A[i][k] * B[k][j]) % m;
}
}
}
return res;
}
}