杭大 1005 Number Sequence
Posted shenyuling
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了杭大 1005 Number Sequence相关的知识,希望对你有一定的参考价值。
Number Sequence
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).
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
原理:MOD7之后肯定有个周期,把他找出来,这题就完成了。具体如下
提示:周期是从第三个数开始,要不然会有下面这种情况
Sample input
7 7 10
则f[i]=1 1 0 0 0 0 0这种序列。很显然,周期是从第三个数开始循环的
#include<stdio.h> int f[10000+5]={1,1,1}; int main() { int a,b,n; while(scanf("%d%d%d",&a,&b,&n),a||b||n) { int i; if(n==2||n==1) { printf("1 "); continue; } for(i=3;i<100;i++)//i<100表示,假定周期不会超过100左右,不过超了就改大一点呗 { f[i]=(a*f[i-1]+b*f[i-2])%7; if((i!=4&&f[i]==f[4]&&f[i-1]==f[3])||i-4>=n) break; } int T=i-2-2;//由于从第三个开始,所以周期T就有这样的表达式 printf("%d ",f[(n-3)%T+3]);//n-3=n-2-1; n-2表示是周期的第n-2个数,再减一,是为了取模时数的范围在0 ——(T-1)
//加三,是因为从第个开始 } return 0; }
以上是关于杭大 1005 Number Sequence的主要内容,如果未能解决你的问题,请参考以下文章