1574 广义斐波那契数列

1574 广义斐波那契数列

 

 时间限制: 1 s
 空间限制: 256000 KB
 题目等级 : 钻石 Diamond
 
 
题目描述 Description

广义的斐波那契数列是指形如an=p*an-1+q*an-2的数列。今给定数列的两系数p和q,以及数列的最前两项a1和a2,另给出两个整数n和m,试求数列的第n项an除以m的余数。

输入描述 Input Description

输入包含一行6个整数。依次是p,q,a1,a2,n,m,其中在p,q,a1,a2整数范围内,n和m在长整数范围内。

输出描述 Output Description

输出包含一行一个整数,即an除以m的余数。

样例输入 Sample Input

1 1 1 1 10 7

样例输出 Sample Output

6

数据范围及提示 Data Size & Hint

数列第10项是55,除以7的余数为6。

分类标签 Tags 点此展开 

 
暂无标签
AC代码1:
#include<cstdio>
#include<cstring>
#define ll long long
#ifdef unix
#define LL "%lld"
#else
#define LL "%I64d"
#endif
using namespace std;
struct node{
    ll a[2][2];
}ans,ss;
ll p,q,a1,a2,n,mod;
inline node mul(node &a,node &b){
    node c;
    for(int i=0;i<2;i++){
        for(int j=0;j<2;j++){
            c.a[i][j]=0;
            for(int k=0;k<2;k++){
                c.a[i][j]=(c.a[i][j]+a.a[i][k]*b.a[k][j])%mod;
            }
        }
    }
    return c;
}
void fpow(ll p){
    for(;p;p>>=1,ss=mul(ss,ss)) if(p&1) ans=mul(ans,ss);
}
int main(){
    scanf(LL LL LL LL LL LL,&p,&q,&a1,&a2,&n,&mod);
    ans.a[0][0]=0;ans.a[0][1]=q;ans.a[1][0]=1;ans.a[1][1]=p;    
    ss.a[0][0]=0;ss.a[0][1]=q;ss.a[1][0]=1;ss.a[1][1]=p;
    n-=2;
    fpow(n);
    printf(LL,(a1*ans.a[0][0]%mod+a2*ans.a[1][0]%mod)%mod);
    return 0;
}
原文地址:https://www.cnblogs.com/shenben/p/5879467.html