码迷,mamicode.com
首页 > 其他好文 > 详细

hdu5187 奇怪题

时间:2015-03-15 12:17:32      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

本来很水的,答案就是(2^n)-2,但是写坑了QAQ

 

因为原题要求答案要mod P,一开始我是这么干的:

        LL ans=pow_mod(2,N,P);
        ans=(ans-2)%P;
        if (N==1)   ans=1%P;
        printf("%I64d\n",ans);

结果WA了= =

其实应该这样:

        LL ans=pow_mod(2,N,P);
        ans=(ans+P-2)%P;
        if (N==1)   ans=1%P;
        printf("%I64d\n",ans);

 

注意ans=(ans+P-2)%P这里

因为ans是快速幂取模之后的值,所以可能这个余数小于2。如果这里直接-2就完蛋了。所以要先加个P

 

 

附AC Code

那个奇怪的快速幂模板棒棒哒~中间过程也不会超long long

技术分享
 1 //B
 2 
 3 #include <iostream>
 4 #include <cstdio>
 5 using namespace std;
 6 #define LL long long
 7 
 8 LL func(LL a,LL b,LL c)     //a*b%c
 9 {
10     long long ret = 0;
11     while (b)
12     {
13         if (b & 1)
14             ret = (ret + a) % c;
15         a = 2 * a % c;
16         b >>= 1;
17     }
18     return ret;
19 }
20 LL pow_mod(LL a,LL b,LL MOD)
21 {
22     if (a==1)   return 1;
23     LL t=a%MOD,ans=1;
24     while(b)
25     {
26         if (b&1)
27             ans=func(ans,t,MOD);
28         t=func(t,t,MOD);
29         b>>=1;
30     }
31     return ans;
32 }
33 
34 int main()
35 {
36     LL N,P;
37     while(~scanf("%I64d%I64d",&N,&P))
38     {
39         LL ans=pow_mod(2,N,P);
40         ans=(ans+P-2)%P;
41         if (N==1)   ans=1%P;
42         printf("%I64d\n",ans);
43     }
44 
45 }
View Code

 

hdu5187 奇怪题

标签:

原文地址:http://www.cnblogs.com/pdev/p/4339059.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!