hdu5187 快速乘法:long long相乘再取模

比如a*b

if b%2==1 res=(res+a)%p

else a=(a+a)%p

b/=2;

==

不错好思想,学习了

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 using namespace std;
 5 #define LL long long
 6 LL mul(LL a,LL b,LL p)
 7 {
 8   LL res=0;
 9   while (b)
10   {
11     if (b&1) res=res+a;
12       if (res>=p) res-=p;
13     a=a+a;
14       if (a>=p) a-=p;
15     b/=2;
16   }
17   return res;
18 }
19 LL quick(LL n,LL p)
20 {
21   LL ans=1,a=2;
22   while (n)
23   {
24     if (n%2) ans=mul(ans,a,p);
25     n/=2;
26     a=mul(a,a,p);
27   }
28   return ans;
29 }
30 int main()
31 {
32   LL n,p,x;
33   while (~scanf("%I64d%I64d",&n,&p))
34   {
35     if (n==1) {printf("%I64d\n",n%p); continue; }
36     x=quick(n,p);
37     x=(x+p-2)%p;
38     printf("%I64d\n",x);
39   }
40 }
View Code

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5187

转载于:https://www.cnblogs.com/xiao-xin/articles/4338562.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值