您的位置:首页 > 产品设计 > UI/UE

HDOJ 1005 Number Sequence

2014-05-15 16:03 381 查看
[align=left]Problem Description[/align]
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).

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each test case, print the value of f(n) on a single line.

[align=left]Sample Input[/align]

1 1 3
1 2 10
0 0 0

[align=left]Sample Output[/align]

2
5

这个题目要求计算指定的数列,开始计算时直接for循环来计算要求的数据,但是提交上去后发现超时了。
后来发现这个题目的数列肯定是有周期的,只要求出这个周期即可解决这个问题....但是其周期也是从第3项开始,如果从第一项计算时提交上去出现WA,网上查找资料后发现,这个数列的周期要从第3项开始。如果从第一项开始时,7、7、10时,其周期是1、1、0、0、0.......这样不可能计算出周期,所以应该从第3项开始计算其周期。

#include <iostream>
using namespace std;
#define Max 100
int main()
{
unsigned int A,B,n,result,fn[Max]={0};
int i=0;
unsigned int f1,f2;
cin>>A>>B>>n;
while(A||B||n)
{
f1=1;
f2=1;
fn[0]=(A*f1+B*f2)%7;
fn[1]=(A*fn[0]+B*f2)%7;
for(i=2;i<=n;i++)
{
fn[i]=(A*fn[i-1]+B*fn[i-2])%7;
if(fn[i-1]==fn[0]&&fn[i]==fn[1])
{
result=fn[(n-3)%(i-1)];//求出周期
break;
}
}
if(n==1||n==2)
{
cout<<f1<<endl;
}
else
cout<<fn[(n-3)%(i-1)]<<endl;
cin>>A>>B>>n;
}
return 0;
}


心得:计算这种数列时,必须要对其周期进行计算,这样能够节省大量时间....
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: