等比数列求和 再取余

2019河北省大学生程序设计竞赛

Icebound and Sequence

分析:

1、等比数列求和   \frac{q\left ( q^{n}-1 \right )}{q-1}    mod p       因为不能保证 p 是素数,所以不能对(q-1)求逆元 ..  法一终..(待补)

--------------------------------------------   哦吼吼~                        如果有下面的公式,那不就不用求逆元啦~  但是需要注意快速幂可能会爆long long...所以加个快速乘...解决

解题来源-clink

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll q,n,p;
ll mulit(ll x,ll y) { ///p=p*(q-1)  直接用快速幂会爆ll
	ll cnt=0;
	while(y) {
		if(y&1)
			cnt=(cnt+x)%p;
		x=2*x%p;
		y>>=1;
	}
	return cnt;
}
ll pow(ll x,ll y,ll mod) {
	ll ans=1;
	while(y) {
		if(y&1)
			ans=mulit(ans,x)%mod;///需要快速乘
		y>>=1;
		x=mulit(x,x)%mod;
	}
	return ans;
}
int main() {
	int t;
	cin>>t;
	while(t--) {
		cin>>q>>n>>p;
		p=(q-1)*p;
		ll ans=(pow(q,n+1,p)-q+p)%p/(q-1);
		cout<<ans<<endl;
	}
	return 0;
}

2、用二分方法,递归搜索,举个栗子:

当项数 n 为偶数:q^{1}+q^{2}+q^{3}+q^{4}+q^{5}+q^{6}            =     q^{1}+q^{2}+q^{3}+(q^{1}+q^{2}+q^{3})*q^{3}             =     (q^{3}+1)*(q^{1}+q^{2}+q^{3})                      其中 mid =(1+n) / 2;

当项数 n 为奇数:q^{1}+q^{2}+q^{3}+q^{4}+q^{5}+q^{6}+q^{7}   =     q^{1}+q^{2}+q^{3}+q^{4}+q^{4}*(q^{1}+q^{2}+q^{3})     =     q^{4}+(q^{4}+1)*(q^{1}+q^{2}+q^{3})   ....

CODE:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll q,n,p;
ll pow(ll x,ll y,ll mod) {
	ll ans=1;
	while(y) {
		if(y&1)
			ans=ans*x%mod;
		y>>=1;
		x=x*x%mod;
	}
	return ans;
}
ll solve(ll r,ll u,ll mod) {
	if(r==1)return u%mod;
	int mid=(r+1)>>1;
	if(r%2==0)
		return ((pow(u,mid,mod)+1)*solve(mid,u,mod)%mod)%mod;
	else
		return (pow(u,mid,mod)+(pow(u,mid,mod)+1)*solve(mid-1,u,mod)%mod)%mod;
}
int main() {
	int t;
	cin>>t;
	while(t--) {
		cin>>q>>n>>p;
		if(q==1)cout<<n%p<<endl;
		else cout<<solve(n,q,p)<<endl;
	}
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嵩韵儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值