递推:Number Sequence(mod找规律)

来源:互联网 发布:ncre vb 编辑:程序博客网 时间:2024/05/19 13:24

解题心得:
1、对于数据很大,很可怕,不可能用常规手段算出最后的值在进行mod的时候,可以思考找规律。
2、找规律时不必用手算(我傻,用手算了好久)。直接先找前100项进行mod打一个表出来,直接看就行了。
3、对于像斐波那契数列(本题)的那样,凭借肉眼无法找到规律的时候,可以观察本题的特点。那就是,第一项和第二项不会变,都为1,1。所以循环的时候必定是以1、1为开始,中间的数可以直接记录,很玄幻。
4、还是边界问题,这很重要,这时候数列尽量从1开始,因为在询问的时候都是询问的第n个数,要时刻保持清醒不然要弄得自己很混乱,比如n 个循环一次那么,m%n == 0的时候刚好是最后一个,m%n == 1的时候才是第一个。

题目:

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
5

#include<stdio.h>int main(){    int num[100];    int a,b,n,i;    num[0]= 1;//从一开始其实更简单    num[1]= 1;    while(scanf("%d%d%d",&a,&b,&n)!=EOF)    {        if(a == 0 && b == 0 && n == 0)            break;        for(i=2;i<50;i++)/*由于f(n)是由前两个数字组合产生,那么只要有两个数字组合相同的情况发生就一定一会产生循环!两个数字的组合的最大可能值为7x7=49,因此只要在调用迭代方法中限制n的在0~48就可以了*/        {            num[i] = (a*num[i-1] + b*num[i-2])%7;            if(num[i] == 1 && num[i-1] == 1)                break;        }        n = n%(i-1);        if(n == 0)//这里需要讨论,注意是i-2,第i-1项,数列中第i-2printf("%d\n",num[i-2]);        else            printf("%d\n",num[n-1]);    }}
0 0
原创粉丝点击