Pentium.Labs

System全家桶:https://zhuanlan.zhihu.com/c_1238468913098731520

导航

hdu5187 奇怪题

本来很水的,答案就是(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

 

posted on 2015-03-15 11:56  Pentium.Labs  阅读(259)  评论(0编辑  收藏  举报



Pentium.Lab Since 1998