zoukankan      html  css  js  c++  java
  • 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
    ",ans);

    结果WA了= =

    其实应该这样:

            LL ans=pow_mod(2,N,P);
            ans=(ans+P-2)%P;
            if (N==1)   ans=1%P;
            printf("%I64d
    ",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
    ",ans);
    43     }
    44 
    45 }
    View Code
  • 相关阅读:
    剑指offer-二进制中1的个数
    [SHOI 2017] 分手是祝愿
    [SCOI 2010] 字符串
    [BZOJ 2653] middle
    [APIO 2015] 雅加达的摩天楼
    [NOI 2015] 品酒大会
    [SDOI 2015] 星际战争
    [Codeforces 715C] Digit Tree
    [TJOI 2018] 智力竞赛
    [CTSC 2018] 混合果汁
  • 原文地址:https://www.cnblogs.com/pdev/p/4339059.html
Copyright © 2011-2022 走看看