快速幂

Time Limit: 1sec    Memory Limit:256MB
Description

输入a和b和p,输出(a^b)%p的值

Input

三个整数:

a,b,p          (2<=a<=100, 0<=b<=1000000000,  3<=p<=10000)

Output

(a^b)%p的值

Sample Input
 Copy sample input to clipboard
2 3 5
Sample Output
3
Hint

a^4=(a^2)*(a^2)

(a*b)%p=((a%p)*(b%p))%p;


Problem Source: ExerciseVI: Adversity leads to prosperity





题解:此题若直接求幂,必然会超时。没关系,我们可用快速幂来规避超时的问题。我们发现,例如,11的二进制表达为:1011。 11%2==1 , 恰好是倒数第一位的数字。5(11/2) %2==1,恰好是倒数第二位的数字。2(5/2)%2==0,恰好是倒数第三位的数……因此我们可以吧a^11分解成a^(2^8+2^1+2^0)。由于要防止中间运算出现溢出错误,因此每步运算都要进行取模。




06. #include<iostream>
07. using namespace std;
08.  
09. int main()
10. {
11. int a,b,p;
12. cin >>a >>b >>p;
13. int x=a;
14. int result=1;
15. while(b)
16. {
17. if(b%2==1)
18. {
19. result=((result%p)*(x%p))%p;
20. }
21. x=(x%p)*(x%p);
22. b=b/2;
23. }
24. cout <<result <<endl;
25. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值