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

posted on 2015-03-14 23:26  xiao_xin  阅读(267)  评论(0编辑  收藏  举报

导航