快速幂(递归)

一个数的整数次幂,是我们在计算中经常用到的,但是怎么可以在 O(log(n)) 的时间内算出结果呢?

代码框中的代码是一种实现,请分析并填写缺失的代码,求 x^y mod p 的结果。

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
#include <set>
using namespace std;
const int maxn = 5e4+10; 
#define inf 0x3f3f3f3f
int x,p,y;

int pw(int x,int y,int p){
	if(y==0){
		return 1;
	}
	int res=pw(x*x,y>>1,p);
	cout<<res<<endl;
	if(y&1){
		res=res*x%p;
	}
	return res;
} 

int main(){
	int x,y,p;
	cin>>x>>y>>p;
	cout<<pw(x,y,p)<<endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值