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

HDU 1005 Number Sequence 数学题

2016-02-02 18:19 513 查看
[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
题目就是给你一条递推式,让你求第n项的大小。

假如直接模拟,会超时,因为它可以给你求很后面的数据,所以不能直接模拟。

所以就考虑有没有循环,看到题目的递推式里对于7取模,只有两个变量共有7*7=49种可能,所以可以对所有的可能进行枚举,然后对求的数对49取模就可以过了。

代码如下:

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
int main(){
int a,b,n;
int ans[200];
scanf("%d %d %d",&a,&b,&n);
while(n!=0)
{
ans[1]=1;
ans[2]=1;
int i=3;
for ( ;i<=100;++i)
{
ans[i]=(ans[i-1]*a+ans[i-2]*b)%7;
}
n=n%49;
printf("%d\n",ans
);
scanf("%d %d %d",&a,&b,&n);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: