HDU 1005 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).

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

分析:
首先考虑一下这道题的n的范围,n的范围是比较大的,我们虽然用数组可以存贮下来但是却会超内存,那么这个问题应该怎么解决的?

最后要求求得的答案对于7取余,那么所有的f(i)肯定都是0~6之内的数字,这样的话我们应该可以找到f(i)和f(i-1)使得两个值均为1,这样的话也就相当于又回到了最起始的状态,也就可以认为函数f()时一个以i-2位周期的周期函数。

知道周期函数后,将n的值对应成周期函数的下标。

代码:

#include<string.h>
#include<stdio.h>
#include<iostream>
using namespace std;
int c[200];
int a,b,n;

int main()
{
    c[1]=1;
    c[2]=1;
    while(~scanf("%d%d%d",&a,&b,&n)&&a&&b&&n)
    {
        if(n>=3)
        {
            int i;
            for(i=3; i<200; i++)
            {
                c[i]=(a*c[i-1]+b*c[i-2])%7;
                if(c[i]==1&&c[i-1]==1)//又回归到最起始的状态,相当于在c这个数组里面i-2个数为一个周期
                    break;
            }
            i-=2;//周期长度
            n=n%i;//需要求的是这个周期里面的第几个数
            if(n==0)
                printf("%d
",c[i]);
            else
                printf("%d
",c[n]);
        }
        else printf("1
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/cmmdc/p/8714590.html