UVA10689-Yet another Number Sequence(矩阵快速幂)

Let’s define another number sequence, given by the following function:
f(0) = a
f(1) = b
f(n) = f(n − 1) + f(n − 2), n > 1
When a = 0 and b = 1, this sequence gives the Fibonacci Sequence. Changing the values of a and
b, you can get many different sequences. Given the values of a, b, you have to find the last m digits of
f(n).
Input
The first line gives the number of test cases, which is less than 10001. Each test case consists of a
single line containing the integers a b n m. The values of a and b range in [0, 100], value of n ranges in
[0, 1000000000] and value of m ranges in [1, 4].
Output
For each test case, print the last m digits of f(n). However, you should NOT print any leading zero.
Sample Input
4
0 1 11 3
0 1 42 4
0 1 22 4
0 1 21 4
Sample Output
89
4296
7711
946

题意:给定一个斐波那契的前两位数求F(n)的后m位

思路:矩阵快速幂
在这里插入图片描述
AC代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
#define ll long long
ll mod;
const int N=2;
int tmp[N][N];
void multi(int a[][N],int b[][N],int n)
{
    memset(tmp,0,sizeof tmp);
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
        for(int k=0;k<n;k++)
        {
            tmp[i][j]=(tmp[i][j]+a[i][k]*b[k][j])%mod;
        }
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
        a[i][j]=tmp[i][j]%mod;
}
int res[N][N];
void Pow(int a[][N],int n)
{
    memset(res,0,sizeof res);
    for(int i=0;i<N;i++) res[i][i]=1;
    while(n)
    {
        if(n&1)
            multi(res,a,N);
        multi(a,a,N);
        n>>=1;
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int a,b,m;
        ll n;
         scanf("%d%d%lld%d",&a,&b,&n,&m);
        mod=1;
       while(m--)
       {
           mod*=10;
       }
         if(n==0)
        {
            printf("%d\n",a%mod);continue;
        }
        if(n==1)
        {
            printf("%d\n",b%mod);continue;
        }
        int x[N][N];
        int y[N][N];
        x[0][0]=1;
        x[1][0]=1;
        x[0][1]=1;
        x[1][1]=0;
        y[0][0]=b;
        y[1][0]=a;
        Pow(x,n-1);
        multi(res,y,2);
        printf("%d\n",res[0][0]);
    }
}

这该死的pow函数,开方有误差可以理解,为什么次方还有误差,卡了我两个小时。。。。
注:pow大于一万的时候产生为1的误差

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值