【每日刷题】 Number Sequence

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sd4567855/article/details/86693521

day29, 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

解答:这道题与求斐波那契数类似。我想到的方法有:
方法一:(爬梯子),设置两个变量分别对应 f(n - 1) 和 f(n - 2),以此往复求f(n). 但可惜,超时。
方法二:矩阵法。这种方法的时间/空间复杂度为O(logN)量级,是解决该类问题的最好方法。我在这里没有尝试。
方法三。利用题目的特性。不同于单纯求斐波那契数列,这里有一个题目限制,f(n)为每次求和后对7取模,如此的一个结果便是会产生一个循环。我们只要求出这个循环数列,再取模即可。
求循环序列时需要注意的一点:要舍弃f(1) = 1, f(2) = 1这两个元素,因为循环很有可能不包含这两个数。

代码:

int main(){
    int A,B;
    int n;
    cin>>A>>B>>n;
    int record[1000] = {1,1};

    while( 1){
        if( A == 0 && B == 0 && n == 0)
            break;
        int cycle_size = 0;
        for( int i = 0; i < 1000; i++){
            if( i == 0)
                record[i] =  (A * 1 + B * 1) % 7;
            else if( i == 1)
                record[i] =  (A * record[0] + B * 1) % 7;
            else
                record[i] = (A * record[i-1] + B * record[i-2]) % 7;

            if( i > 2)
                if( record[i] == record[cycle_size])
                    cycle_size++;
                else
                    cycle_size = 0;

        }
        cycle_size = 1000 - cycle_size;
        n-=2;
        cout<<record[(n-1) % cycle_size]<<endl;
        cin>>A>>B>>n;
    }
return 0;}

运行结果:image.png-30.4kB


我的微信公众号

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sd4567855/article/details/86693521