题目:
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
解题思路:
- 打表法判断循环周期。判断过程,因为1,1必存在,所以,可以以1,1,一次循环出现的间隔长度为循环周期。
- 注意特殊情况。当A=0,B=0,或者,A=7,B=14等情况存在时循环周期不存在。即序列的规律为1,1,0,0,…此处必须分开考虑
循环周期的长度并不一定是48,网上一些题解说周期是48是不对的,实际上大部分循环周期是48,但是,还有很多例外的情况。
附上代码:
#include<stdio.h> using namespace std; int arr[100]; int main() { int a,b,cnt,i; long n; while(~scanf("%d%d%ld",&a,&b,&n)&&(a||b||n)){ arr[1]=1; arr[2]=1; cnt=0; for(i=3;i<100;i++){ arr[i]=(a*arr[i-1]+b*arr[i-2])%7; if(arr[i]==1&&arr[i-1]==1)break;//周期为i-2的原因 if(arr[i]==0&&arr[i-1]==0){cnt=1;break;}//1,1,0,0,0...的情况 } if(cnt==1){ if(n>2)printf("0\n"); else{ printf("1\n"); } continue;//一定不能少 }//对1,1,0,0,0...情况的分析 i=i-2;//周期为i-2 //周期为i-2的原因,见上面 if(n<i){printf("%d\n",arr[n]);continue;} if(n%i==0){printf("%d\n",arr[i]);continue;} n=n%i; printf("%d\n",arr[n]); } }