Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 224146 Accepted Submission(s): 56799
Problem Description
A number sequence is defined as follows:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
Input
The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
Output
For each test case, print the value of f(n) on a single line.
Sample Input
1 1 3
1 2 10
0 0 0
Sample Output
2
5
找規律
Code1:
#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
int main()
{
int n,a,b;
int f[1000];
f[1]=1;
f[2]=1;
while(cin>>a>>b>>n)
{
if(a==0&&b==0&&n==0)break;
n%=48;
for(int i=3;i<=n;i++)
{
f[i]=f[i-1]*a+f[i-2]*b;
f[i]%=7;
}
printf("%d\n",f[n]);
}
return 0;
}
矩陣快速冪:
#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
struct mat{
ll a[2][2];
};
mat mat_mul(mat x,mat y)
{
mat res;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
{
res.a[i][j]=0;
for(int k=0;k<2;k++)
res.a[i][j]=(res.a[i][j]+x.a[i][k]*y.a[k][j]%7)%7;
}
return res;
}
int main()
{
int a,b,n;
while(cin>>a>>b>>n)
{
if(!a&&!b&&!n)break;
if(n<=2)
{
cout<<"1"<<endl;
continue;
}
mat aa,ans;
aa.a[0][0] = a;
aa.a[0][1] = b;
aa.a[1][0] = 1;
aa.a[1][1] = 0;
ans.a[0][0] = ans.a[1][1] = 1;
ans.a[0][1] = ans.a[1][0] = 0;
n -= 2;
while(n)
{
if(n&1)ans=mat_mul(ans,aa);
aa=mat_mul(aa,aa);
n>>=1;
}
cout<<(ans.a[0][0]+ans.a[0][1])%7<<endl;
}
return 0;
}