[数论]Number Sequence

来源:互联网 发布:学象棋的软件 编辑:程序博客网 时间:2024/04/30 11:58

Number Sequence

时间限制: 1000MS   内存限制: 65536KByte   64位IO格式:%I64d & %I64u
描述
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).
输入
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.
输出
For each test case, print the value of f(n) on a single line.
样例输入
1 1 31 2 100 0 0
样例输出
25
代码:
     
#include<stdio.h>int r[100];int main(){int a,b,n;    int i,j,k;   r[0]=r[1]=r[2]=1;while(scanf("%d%d%d",&a,&b,&n),a|b|n){int flag=0;int begin;    int end;for(i=3;i<=n&&!flag;i++){r[i]=(a*r[i-1]+b*r[i-2])%7;for(j=2;j<=i-1;j++){if(r[i]==r[j]&&r[i-1]==r[j-1])    {    end=i;      begin=j;    flag=1;    break;    }  } } if(flag){printf("%d\n",r[(n-begin+1)%(end-begin)+begin-1]);}else printf("%d\n",r[n]);}} 

0 0