Generalized Fibonacci Sequence#
Problem Description#
The generalized Fibonacci sequence is defined as a sequence of the form .
Given the coefficients and of the sequence, as well as the first two terms and , and two integers and , find the remainder of the th term modulo .
Input Format#
The input consists of a single line containing six integers: .
Output Format#
The output consists of a single line containing an integer representing the answer.
Example #1#
Input Example #1#
1 1 1 1 10 7
Output Example #1#
6
Hint#
The 10th term of the sequence is 55, and .
【Data Range】
For 100% of the data, , and .
Problem Analysis#
The problem requires the value of .
To solve this, we need to find the nth term and then take the remainder. The problem already provides the recursive formula . A brute force approach would be to start from the 3rd term and enumerate each term until the nth term is reached. The time complexity of this approach is . However, the data range of this problem is large, and the brute force approach will exceed the time limit. Therefore, we need to accelerate the process of finding the nth term.
To accelerate the recursive process, we can try using matrix exponentiation.
Let matrix A be: [].
This means that
Combining this with the recursive formula , we can deduce that the acceleration matrix B is
We can observe that each multiplication of matrix B corresponds to moving one term forward. Therefore, finding the nth term becomes finding the first column of , and we can use matrix exponentiation to solve it in time complexity.
Code Implementation#
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll p,q,a1,a2,n,M;
struct matrix{ll m[5][5];};
matrix operator *(const matrix &a,const matrix &b){
matrix c;
memset(c.m,0,sizeof(c.m));
for(int i=1;i<=2;i++)
for(int j=1;j<=2;j++)
for(int k=1;k<=2;k++)
c.m[i][j]=(c.m[i][j]+a.m[i][k]*b.m[k][j])%M;
return c;
}
matrix fastPow(matrix a,int n){
matrix ans;
memset(ans.m,0,sizeof(ans.m));
for(int i=1;i<=2;i++) ans.m[i][i]=1;
while(n){
if(n&1) ans=ans*a;
a=a*a;
n>>=1;
}
return ans;
}
int main(){
matrix a,b;
memset(a.m,0,sizeof(a.m));
memset(b.m,0,sizeof(b.m));
cin>>p>>q>>a1>>a2>>n>>M;
a.m[1][1]=a1;a.m[1][2]=a2;
b.m[1][1]=0;b.m[1][2]=q;
b.m[2][1]=1;b.m[2][2]=p;
matrix c=a*fastPow(b,n-1);
cout<<c.m[1][1];
return 0;
}