快速幂+等比数列求和取模

公比为k的等比数列之和T[n]

当n为偶数时T[n] = T[n/2] + pow(k,n/2) * T[n/2]

n为奇数T[n] = T[n/2] + pow(k,n/2) * T[n/2] + 等比数列第n个数的值

#include
using namespace std;
#define ll long long

ll x,mod;

ll q_pow(ll x,ll n,ll mod){
	ll res=1;
	while(n){
		if(n&1)res=res*x%mod;
		x=x*x%mod;
		n>>=1;
	}
	return res%mod;
}

ll sum(ll n){
	if(n<=1)return x%mod;
	
	ll s=sum(n/2)%mod;
	
	if(n%2==0)return s + s*q_pow(x,n/2,mod)%mod;
	else return s + s*q_pow(x,n/2,mod) + q_pow(x,n,mod)%mod;
}

int main(){
	int pa;
	cin>>pa;
	for(int pass=1;pass<=pa;pass++){
		ll n;

		scanf("%lld%lld%lld",&x,&n,&mod);
		cout<

 

你可能感兴趣的:(快速幂+等比数列求和取模)