1005 Number Sequence(广义斐波那契数列)

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

网上的题解都是找规律,那如果mod再大一点就不行了,所以我用快速矩阵幂做的,适用于广义斐波那契数列

#include
using namespace std;
const int mod=7;
using LL=int64_t;
struct Node {
    LL m[3][3];
}sum,base;

Node muilt(Node a,Node b) {
    Node temp;
    for(int i=0;i<2;i++) {
        for(int j=0;j<2;j++) {
            temp.m[i][j]=0;
            for(int k=0;k<2;k++)
            temp.m[i][j]=(a.m[i][k]*b.m[k][j]+temp.m[i][j])%mod;
        }
    }
    return temp;
}

LL q_mod(LL a,LL b,LL n) {
    sum.m[0][0]=sum.m[1][0]=1;
    sum.m[0][1]=sum.m[1][1]=0;
    base.m[0][0]=a%mod;
    base.m[0][1]=b%mod;
    base.m[1][0]=1,base.m[1][1]=0;
    n-=2;
    while(n) {
        if(n&1) sum=muilt(base,sum);
        n>>=1;
        base=muilt(base,base);
    }
    return sum.m[0][0];
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    LL a,b,n;
    while(cin>>a>>b>>n&&a&&b&&n) {
        if(n<=2) {
            if(n==1) cout<else if(n==2) cout<else cout<return 0;
}

你可能感兴趣的:(HDU,oj)