【Comet OJ

Description

传送门
在这里插入图片描述
T<=1e5n,a,b,p(1n,a,b,p1018)T<=1e5组数据,每组读入n,a,b,p (1≤n,a,b,p≤10^{18} )

Solution

  • aia^i化为(a)2i(sqrt{a})^{2i},然后就可以将i化为2i,再根据这个式子的形式显然是与(a+b)n(a+b)^n是一样的
  • 但是我们由于枚举的是2i2i,所以我们只需要偶数项。但是我们可以发现,如果次数是奇数的话,一定还留有asqrt{a}
  • 所以只需要取(a+b)n(sqrt{a}+b)^n 最后的整数就好了,剩下一个kak sqrt{a}是奇数项的贡献。
  • 快速幂即可。
#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
");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());
	}
}

原文地址:https://www.cnblogs.com/DeepThinking/p/13090937.html