杭电ACM 1005 Number Sequence

来源:互联网 发布:赛飞软件 编辑:程序博客网 时间:2024/06/07 01:45
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 31 2 100 0 0
 

Sample Output
25
 

Author
CHEN, Shunbao
 

Source
ZJCPC2004
 

Recommend
JGShining   |   We have carefully selected several similar problems for you:  1008 1021 1019 1009 1012 
 
给出的计算表达式里面有f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.由于这个%符号的存在,所以f(n)的取值只有0-6七种,所以f(n-1)和f(n-2)的取值最多有49种,所以f(n)是个周期数列,并且周期不大于49。由上面思路可以写如下代码:
/************************************************************************//* 1005 Number Sequence                                                *//*由f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.    *//*主要是mod7可以得到f(n)的周期不会超过49                             *//************************************************************************/#include <iostream>using namespace std;int f[60];int T;int main(){int a, b ,n;f[1] = 1;f[2] = 1;while (cin>>a>>b>>n && a && b && n ){if (n==1 || n==2){cout << f[n] << endl;}else{for (int i = 3; i < 60; i++){f[i] = (a*f[i - 1] + b*f[i - 2]) % 7;if (f[i] == 1 && f[i - 1] == 1){T = i ;break;}}if (n>T){n = n % (T-2);if (n==0){n = T-2;}}cout << f[n] << endl;}}return 0;}


但是发现一个问题:将T=T-2放在if(n>T)之前会发生无法ac的情况,跪求大神和各位兄弟姐妹指导。代码如下:
/************************************************************************//* 1005 Number Sequence                                                *//*由f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.    *//*主要是mod7可以得到f(n)的周期不会超过49                             *//************************************************************************/#include <iostream>using namespace std;int f[60];int T;int main(){int a, b ,n;f[1] = 1;f[2] = 1;while (cin>>a>>b>>n && a && b && n ){if (n==1 || n==2){cout << f[n] << endl;}else{for (int i = 3; i < 60; i++){f[i] = (a*f[i - 1] + b*f[i - 2]) % 7;if (f[i] == 1 && f[i - 1] == 1){T = i ;break;}}T = T - 2;if (n>T){n = n % T;if (n==0){n = T;}}cout << f[n] << endl;}}return 0;}


0 0
原创粉丝点击