【费马小定理+矩阵快速幂】HDU4549——M斐波那契数列

【题目大意】

M斐波那契数列F[n]是一种整数数列,它的定义如下:
F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n > 1 )
现在给出a, b, n,求出F[n]的值。

【思路】

【费马小定理+矩阵快速幂】HDU4549——M斐波那契数列

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 typedef long long ll;
 7 const ll MOD=1000000007;
 8 int a,b,n;
 9 
10 void mul(ll A[][2],ll B[][2])
11 {
12     ll C[2][2];
13     memset(C,0,sizeof(C));
14     for (int i=0;i<2;i++)
15         for (int j=0;j<2;j++)
16             for (int k=0;k<2;k++) 
17                 C[i][j]=(C[i][j]+A[i][k]*B[k][j])%(MOD-1);
18     for (int i=0;i<2;i++)
19         for (int j=0;j<2;j++) B[i][j]=C[i][j];
20 }
21 
22 void fibonacci(ll &fa,ll &fb)
23 {
24     ll acc[2][2]={{1,1},{1,0}};
25     ll now[2][2]={{1,0},{0,1}};
26     int res=n-1;
27     while (res>0)
28     {
29         if (res&1) mul(acc,now);
30         mul(acc,acc);
31         res>>=1;
32     }
33     fa=now[0][1];
34     fb=now[0][0];
35 }
36 
37 ll get_ans(ll x,ll p)
38 {
39     ll now=x;
40     ll res=p;
41     ll ret=1;
42     while (res>0)
43     {
44         if (res&1!=0) ret=(ret*now)%MOD;
45         now=(now*now)%MOD;
46         res>>=1;
47     }
48     return ret;
49 }
50 
51 int main()
52 {
53     while (~scanf("%d%d%d",&a,&b,&n))
54     {
55         if (n==0) cout<<a<<endl;
56         else if (n==1) cout<<b<<endl;
57         else
58         {
59             ll fa=0,fb=0;
60             fibonacci(fa,fb);
61             printf("%lld
",(get_ans(a,fa)*get_ans(b,fb))%MOD); 
62         }
63     }
64     return 0;
65 }

【附录:用多维数组名作函数参数


如果用二维数组名作为实参和形参,在对形参数组声明时,必须指定第二维(即列)的大小,且应与实参的第二维的大小相同。第一维的大小可以指定,也可以不指定。如:
  int array[3][10];  //形参数组的两个维都指定
  int array[][10];  //第一维大小省略

二者都合法而且等价。但是不能把第二维的大小省略。下面的形参数组写法不合法:
  int array[][];  //不能确定数组的每一行有多少列元素
  int array[3][];  //不指定列数就无法确定数组的结构
在第二维大小相同的前提下,形参数组的第一维可以与实参数组不同。例如,实参数组定义为:int score[5][10]; 而形参数组可以声明为:
  int array[3][10];  //列数与实参数组相同,行数不同
  int array[8][10];

这时形参二维数组与实参二维数组都是由相同类型和大小的一维数组组成的,实参数组名score代表其首元素(即第一行)的起始地址,系统不检查第一维的大小。
如果是三维或更多维的数组,处理方法是类似的。