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

相关文章:

  • 2022-12-23
  • 2021-11-15
  • 2021-12-18
  • 2022-01-20
  • 2021-09-22
  • 2021-06-24
猜你喜欢
  • 2021-08-04
  • 2021-10-06
  • 2022-12-23
  • 2021-12-14
  • 2022-01-07
  • 2021-09-07
相关资源
相似解决方案