类似斐波那契数的求解(利用周期)

题目出处(点击)
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.
题意:
就是斐波那契数列的拓展,只不过正常求解会超时。
思路:
可以发现它是对7取余,这样可以确定它一定有周期。

直接上代码,带注释:

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
	int A,B,n,i,T;
    int a[1000];
    cin >> A >> B >> n;
    while( A!=0 || B!=0 || n!=0)
    {
        a[2]=1;
		a[1]=1;
        for(i=3;i<1000;i++)
		{ 
            a[i] = ( A * a[i-1] + B * a[i-2]) % 7;
       		 if(a[i] == 1 && a[i-1] == 1)              //求周期
                break;
		} 
        T=i-2;
        if(n%T==0) cout<<a[T]<<endl;    		//利用周期
        else cout<<a[n%T]<<endl;
        cin >> A >> B >> n;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46687179/article/details/105667653