天天看点

【hdu1005】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.

闲谈:这个题很早就做过了,第一次做用的规律。后来知道还能用矩阵快速幂解,就学了一下又做了一遍。讲一下矩阵快速幂的做法

题解:

题目给你了公式,区别于一般的矩阵快速幂,他给的系数是A,B。我们就来推导一下。

f(n)=A*f(n-1)+B*f(n-2)
f(n+1)=A*f(n)+B*f(n-1)=A^2*f(n-1)+A*Bf(n)*f(n-2)+B*f(n-1);

把基础的:

1 1

1 0

换成

a b

1 0

得到新公式:

【hdu1005】Number Sequence(矩阵快速幂)

让A=

【hdu1005】Number Sequence(矩阵快速幂)

所以f(n)=(A[0][0]+A[0][1])mod7;

不懂矩阵快速幂的来这里看看瞧瞧了^_^

代码:

#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
const int MAX_N=+;
const int mod=;
struct mat
{
    int M[][];
};
int a,b,n;
mat mat_mul(mat x,mat y)
{
    mat res;
    memset(res.M,,sizeof(res.M));
    for(int i=;i<;i++)
        for(int j=;j<;j++)
        for(int k=;k<;k++)
    {
        res.M[i][j]+=x.M[i][k]*y.M[k][j];
        res.M[i][j]%=mod;
    }
    return res;
}
int mod_pow(int N)
{
    mat c,res;
    memset(res.M,,sizeof(res.M));
    c.M[][]=a; c.M[][]=b;
    c.M[][]=; c.M[][]=;
    for(int i=;i<;i++)
        res.M[i][i]=;
    while(N>)
    {
        if(N&) res=mat_mul(res,c);
        c=mat_mul(c,c);
        N>>=;
    }
    return res.M[][]+res.M[][];
}
int main()
{
    while(scanf("%d%d%d",&a,&b,&n)&&a)
    {
        int d=mod_pow(n-)%mod;
        printf("%d\n",d);
    }
    return ;
}