hdu 1005 Number Sequence

Number Sequence

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

这个题目太坑人了,如果定义一个很大的数组,这样会超出空间,如果用递归做,会超时,那如果用循环写呢?告诉你,还是超时。我就是按照上面的来写,结果被坑了好久,无奈之下,只有百度,大佬发现了其中的规律,每隔 48 次答案循环,所以这题的解题关键在这
代码实现:

#include<stdio.h>
#include <iostream>
#include <algorithm>
#include<string.h>
#include<math.h>
int f[10001];
using namespace std;
int main()
{
    int a,b;
    int n;
    while (scanf("%d%d%d",&a,&b,&n) != EOF && a+b+n)
    {
        memset(f,0,sizeof(f));
        f[1] = 1;
        f[2] = 1;
        if (n == 1)
            printf("%d\n",f[1]);
        else if (n == 2)
            printf("%d\n",f[2]);
        else
        {
            n = n % 48;
            for (int i=3;i<=1000;i++)
            {
                 f[i] = (a * f[i-1] + b * f[i-2]) % 7;
            }
            printf("%d\n",f[n]);
        }
   }
    return 0;
}

上一篇:PAT Basic 1005


下一篇:pat 1001-1005