前言
提示:这里可以添加本文要记录的大概内容:
斐波那契数列就是前面俩个数字相加,例如1,1,2,3,5,8,11…
(前面俩个1要相等
提示:以下是本篇文章正文内容,下面案例可供参考
一、斐波那契数列代码
public class FibonacciSeries { public static void main(String[] args) { int n = 10; // 你可以改变这个值来计算斐波那契数列的前n个数 printFibonacciSeries(n); } public static void printFibonacciSeries(int n) { int t1 = 0, t2 = 1; System.out.print("斐波那契数列的前 " + n + " 个数是:"); for (int i = 1; i <= n; ++i) { System.out.print(t1 + " "); int sum = t1 + t2; t1 = t2; t2 = sum; } } }
二、矩阵快速幂(斐波那契)
AcWing 1305. 1303. 斐波那契前 n 项和
前面这个base是指的是(fn,f(n+1),Sn))
res是推出来的公式,由于矩阵乘法中,是列*行=得到的数;
代码如下(示例):
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; } }