HDU--1005--Number Sequence

来源:互联网 发布:职场女性知乎 编辑:程序博客网 时间:2024/06/09 19:18

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


方法一:一开始想找到循环点就break退出,然后输出,但是漏了A和B都是7的倍数时,从第三项开始都是0的这种情况,所以一直过不去,改后ac代码如下:

#include<stdio.h>int main(){int f[10000],i,l,x;int a,b,n;f[1]=1;f[2]=1;while(scanf("%d %d %d",&a,&b,&n),a||b||n){x=0;for(i=3;i<100;i++){f[i]=(a*f[i-1]+b*f[i-2])%7;if(f[i]==1&&f[i-1]==1){l=i-2;break;}if(f[i]==0&&f[i-1]==0){x=1;break;}}if(x==1){printf("0\n");}else{if(n%l!=0)printf("%d\n",f[n%l]);elseprintf("%d\n",f[l]);}}} 

方法二:这是网上大神的一种方法,但是不懂为什么直接取余49就行了,Mark,待解决。

#include<stdio.h>int main(){int a,b,f[10000],i;int n;f[1]=1;f[2]=1;while(scanf("%d %d %d",&a,&b,&n),a||b||n){for(i=3;i<51;i++){f[i]=(a*f[i-1]+b*f[i-2])%7;}printf("%d\n",f[n%49]);}}