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

hdoj 1005 Number Sequence

2015-10-25 20:04 369 查看

Number Sequence

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 133924 Accepted Submission(s): 32531


[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

题解:1、一般这种数值特别大而又给了你一个数组,由数组的前边的项求得后边的项的题都有规律 ,注意找规律
2、f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7. 每个数mod7无非有7种结果 0 1 2 3 4 5 6,我们用同余定理转换f(n)式得f(n) = ((A * f(n - 1))mod7 +( B * f(n - 2))mod7) mod 7.因为我们上边说了mod7只有7种结果,那么根据上式两个对7取模的总共有7*7=49种可能,所以49为一个周期,这样我们只需要求出前49项就可以了

#include<stdio.h>
#include<string.h>
#define MAX 1000
int f[MAX];
void fun(int a,int b)
{
f[1]=f[2]=1;
for(int i=3;i<55;i++)
f[i]=(a*f[i-1]+b*f[i-2])%7;
}
int main()
{
int a,b,c,n,m,i,j;
while(scanf("%d%d%d",&a,&b,&n)&&a!=0&&b!=0&&n!=0)
{
n=n%49;
fun(a,b);
printf("%d\n",f
);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: