首页 > 代码库 > hdu1005

hdu1005

Number Sequence

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


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
 1 #include <stdio.h>
 2 #include <math.h>
 3 #include <string.h>
 4 #include <map>
 5 #include <iostream>
 6 #include <algorithm>
 7 int w[100];
 8 using namespace std;
 9 int main()
10 {
11     int a,b,n,i,flag,first,end,j;
12     while(cin>>a>>b>>n&&(a||b||n))
13     {
14         flag=0;
15         w[0]=1;
16         w[1]=1;
17         w[2]=1;
18         for(i=3;i<=n&&!flag;i++)
19         {
20             w[i]=(a*w[i-1]+b*w[i-2])%7;
21             for(j=2;j<=i-1;j++)
22             {
23                 if(w[i]==w[j]&&w[i-1]==w[j-1])
24                 {
25                     first=j-1;
26                     end=i-1;
27                     flag=1;
28                     break;
29                 }
30             }
31         }
32         if(flag)
33             printf("%d\n",w[first+(n-end)%(end-first)]);
34         else
35             printf("%d\n",w[n]);
36     }
37     return 0;
38 }

 

hdu1005