标签:
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
Sample Output
//下面的代码超时
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<string>
using namespace std;
int f(int A,int B,int n)
{
int i;
if(n==1||n==2)
return 1;
else
{
int x=1,y=1;
int sum;
for(i=3;i<=n;i++)
{
sum= (A * y + B * x) % 7;
x=y;
y=sum;
}
return y;
}
}
int main()
{
int A,B,n;
while(cin>>A>>B>>n)
{
if(A==0&&B==0&&n==0)
break;
int sum=f(A,B,n);
cout<<sum<<endl;
}
return 0;
}
//参照了别人的博客
才知道这道题是有规律的从下面实例中可以得知每48组为一次循环
所以才会超时
a[1]=1 a[2]=1 a[3]=3 a[4]=5 a[5]=4 a[6]=0 a[7]=1 a[8]=1 a[9]=3 a[10]=5
a[11]=4 a[12]=0 a[13]=1 a[14]=1 a[15]=3 a[16]=5 a[17]=4 a[18]=0 a[19]=1
a[20]=1 a[21]=3 a[22]=5 a[23]=4 a[24]=0 a[25]=1 a[26]=1 a[27]=3 a[28]=5
a[29]=4 a[30]=0 a[31]=1 a[32]=1 a[33]=3 a[34]=5 a[35]=4 a[36]=0 a[37]=1 a[38]=1 a[39]=3 a[40]=5 a[41]=4 a[42]=0 a[43]=1 a[44]=1 a[45]=3 a[46]=5 a[47]=4 a[48]=0 a[49]=1 a[50]=1 a[51]=3
a[52]=5 a[53]=4 a[54]=0 a[55]=1 a[56]=1 a[57]=3 a[58]=5 a[59]=4 a[60]=0 a[61]=1 a[62]=1 a[63]=3 a[64]=5 a[65]=4 a[66]=0 a[67]=1a[68]=1 a[69]=3 a[70]=5 a[71]=4 a[72]=0 a[73]=1 a[74]=1 a[75]=3 a[76]=5 a[77]=4 a[78]=0 a[79]=1 a[80]=1 a[81]=3
a[82]=5 a[83]=4 a[84]=0 a[85]=1 a[86]=1 a[87]=3 a[88]=5 a[89]=4 a[90]=0 a[91]=1 a[92]=1 a[93]=3 a[94]=5 a[95]=4 a[96]=0 a[97]=1 a[98]=1
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<string>
using namespace std;
int f(int A,int B,int n)
{
n=n%48;//这样就不会超时
int i;
if(n==1||n==2)
return 1;
else
{
int x=1,y=1;
int sum;
for(i=3;i<=n;i++)
{
sum= (A * y + B * x) % 7;
x=y;
y=sum;
}
return y;
}
}
int main()
{
int A,B,n;
while(cin>>A>>B>>n)
{
if(A==0&&B==0&&n==0)
break;
int sum=f(A,B,n);
cout<<sum<<endl;
}
return 0;
}
Number Sequence
标签:
原文地址:http://blog.csdn.net/phytn/article/details/45193195