Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5905 Accepted Submission(s): 1966


综述得到一个递推式S(n) = 2*a*S(n-1)+(b-a*a)*S(n-2) 这个公式对所有如 (a+sqrt(b))^n%mod形式求整数的式子都适应
我们只需要用矩阵快速幂求这个递推式就行
参考博客:https://blog.csdn.net/chen_ze_hua/article/details/52072732
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <vector>
#include <string>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
#define ls (r<<1)
#define rs (r<<1|1)
#define debug(a) cout << #a << " " << a << endl
using namespace std;
typedef long long ll;
const ll maxn = 2; //数组的大小尽量开的小,开大了会tle!!!
const ll mod = 1e9 + 7;
struct matrix {
ll a[maxn][maxn];
};
matrix ans, base;
ll m;
matrix mul( matrix x, matrix y ) {
matrix tmp;
for( ll i = 0; i < 2; i ++ ) {
for( ll j = 0; j < 2; j ++ ) {
tmp.a[i][j] = 0;
for( ll k = 0; k < 2; k ++ ) {
tmp.a[i][j] = ( tmp.a[i][j] + x.a[i][k]*y.a[k][j] + m ) % m;
}
}
}
return tmp;
}
ll qow( ll n ) {
while( n ) {
if( n&1 ) {
ans = mul( ans, base );
}
base = mul( base, base );
n /= 2;
}
return ans.a[0][0];
}
int main() {
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
ll a, b, n;
while( cin >> a >> b >> n >> m ) {
double tmp = a + sqrt(b);
ll t1 = (ll)(tmp+1), t2 = (ll)(tmp*tmp+1);
base.a[0][0] = 2*a, base.a[0][1] = 1;
base.a[1][0] = (b-a*a+m)%m, base.a[1][1] = 0;
ans.a[0][0] = t2, ans.a[0][1] = t1;
ans.a[1][0] = 0, ans.a[1][1] = 0;
if( n == 1 ) {
cout << t1 << endl;
} else if( n == 2 ) {
cout << t2 << endl;
} else {
cout << qow(n-2) << endl;
}
}
return 0 ;
}
HDU 4565 So Easy! 广义斐波拉数 数论 (a+sqrt(b))^n%mod 模板
原文:https://www.cnblogs.com/l609929321/p/9398349.html