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
  • 相关阅读:
    digitalpersona 开发
    Task 暂停与继续
    IQueryable 和 IEnumerable(二)
    SpringBoot Redis 订阅发布
    @Formula
    Aop 简单实例
    幂等 zuul的Filter实现
    C# async await 举个栗子
    Integer 类和 int 的区别
    TCP和UDP的区别以及各自应用
  • 原文地址:https://www.cnblogs.com/pdev/p/4339059.html
Copyright © 2011-2022 走看看