HDU 1005 Number Sequence (数学规律)

Number Sequence

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


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 
 
 
Author
CHEN, Shunbao
 
Source
 
Recommend
JGShining
 
 
看了大神的代码才知道水题也是要很严谨去对待的啊。
题目主要是要找循环节。
一开始找规律于是又了下面的代码
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<stdlib.h>
 4 #include<algorithm>
 5 using namespace std;
 6 int a[100];
 7 int main()
 8 {
 9     //freopen("in.txt","r",stdin);
10     int n,A,B;
11     while(scanf("%d %d %d",&A,&B,&n)&&(n||A||B))
12     {
13         a[1]=1;
14         a[2]=1;
15         for(int i=3;i<=49;i++)
16             a[i]=(A*a[i-1]+B*a[i-2])%7;
17         printf("%d
",a[n%49]);
18     }
19     return 0;
20 }
View Code

后来发现如果A=7,B=7,n>2的话,输入都应该会是0,但是实际输出为1。虽然数据有点水,所以还是要严谨对待。

做法还是找循环节,只是说多了很多细节,要好好体会。

 1 #include<cstdio>
 2 #include<cmath>
 3 #include<cstring>
 4 #include<stdlib.h>
 5 #include<algorithm>
 6 using namespace std;
 7 const int MAXN=200+10;
 8 int a[MAXN];
 9 int main()
10 {
11     //freopen("in.txt","r",stdin);
12     int A,B,n,i;
13     a[1]=a[2]=1;
14     while(scanf("%d %d %d",&A,&B,&n)!=EOF)
15     {
16         if(A==B&&B==n&&n==0)break;
17         int flag=0;
18         for(i=3;i<=200;i++)
19         {
20             a[i]=(A*a[i-1]+B*a[i-2])%7;
21             if(a[i]==1&&a[i-1]==1) 
22                 break;
23             if(a[i]==0&&a[i-1]==0){
24                 flag=1;break;
25             }   
26         }
27         if(flag)
28         {
29             printf("0
");
30             continue;
31         }
32         if(i>n)
33         {
34             printf("%d
",a[n]);
35             continue;
36         }
37         i=i-2;
38         n=n%i;
39         if(n==0)n=i;
40         printf("%d
",a[n]);
41     }
42     return 0;
43 }
View Code
原文地址:https://www.cnblogs.com/clliff/p/3922881.html