对于求a^n次方,并且得出的数必须取模于2017;
2
#include<iostream>
using namespace std;
#define M 2017
int main()
{
int a = 3;
int r = 1;
int n;
cin >> n;
while(n)
{
if(n&1)
{
r*=a;
}
a = a*a%M;
n/=2;
}
cout << r;
return 0;
}
斐波那契数列
1 1 2 3 5 8…….
第一个:可以发现是后面一个数是前面两个数的和
第二个:从线性代数的角度来看 是有矩阵 1 1 1 0 的幂次积组成
这里根据第二种来做
代码如下
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> vec;
typedef vector<vec> mat;
typedef long long LL;
const int N = 10007;
mat mul(mat a,mat b) //矩阵乘法
{
mat c(a.size(),vec(b[0].size()));
for(int i=0;i<a.size();i++)
{
for(int k=0;k<b.size();k++)
{
for(int j=0;j<b[0].size();j++)
c[i][j] = ( c[i][j] + a[i][k] * b[k][j] ) % N;
}
}
return c;
}
mat solve_pow(mat a,int n) //快速幂
{
mat b(a.size(),vec(a.size()));
for(int i=0;i<a.size();i++)
b[i][i]=1;
while(n>0)
{
if(n & 1)
b=mul(b,a);
a=mul(a,a);
n >>= 1;
}
return b;
}
LL n;
void solve()
{
mat a(2,vec(2));
while(~scanf("%d",&n) && n!=-1)
{
a[0][0]=1,a[0][1]=1;
a[1][0]=1,a[1][1]=0;
a=solve_pow(a,n);
printf("%d\n",a[1][0]);
}
}
int main()
{
solve();
return 0;
}