Description
传送门
T
<
=
1
e
5
组
数
据
,
每
组
读
入
n
,
a
,
b
,
p
(
1
≤
n
,
a
,
b
,
p
≤
1
0
18
)
T<=1e5组数据,每组读入n,a,b,p (1≤n,a,b,p≤10^{18} )
T<=1e5组数据,每组读入n,a,b,p(1≤n,a,b,p≤1018)
Solution
- 将 a i a^i ai化为 ( a ) 2 i (\sqrt{a})^{2i} (a)2i,然后就可以将i化为2i,再根据这个式子的形式显然是与 ( a + b ) n (a+b)^n (a+b)n是一样的
- 但是我们由于枚举的是 2 i 2i 2i,所以我们只需要偶数项。但是我们可以发现,如果次数是奇数的话,一定还留有 a \sqrt{a} a。
- 所以只需要取 ( a + b ) n (\sqrt{a}+b)^n (a+b)n 最后的整数就好了,剩下一个 k a k \sqrt{a} ka是奇数项的贡献。
- 快速幂即可。
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll __int128
using namespace std;
int T;
ll A,B,n,p;
void read(ll &x){
x=0; char ch=getchar();
for(;ch<'0'||ch>'9';ch=getchar());
for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
}
int pd[50];
void write(ll x){
if (!x) {printf("0\n");return;}
while (x) pd[++pd[0]]=x%10,x/=10;
while (pd[0]) putchar(pd[pd[0]--]+'0');
puts("");
}
struct num{
ll x,y;
num(ll _x,ll _y){x=_x,y=_y;}
};
num operator *(num a,num b){return num((a.x*b.y+b.x*a.y)%p,(a.x*b.x%p*A+a.y*b.y)%p);}
ll qp(){
num s=num(0,1),x=num(1,B);
for(;n;n/=2,x=x*x) if (n&1)
s=s*x;
return s.y;
}
int main(){
freopen("ceshi.in","r",stdin);
scanf("%d",&T);
while (T--){
read(n),read(A),read(B),read(p);
A=A%p,B=B%p;
write(qp());
}
}