FZU-1752.(A^B mod C)(快速幂与快速乘优化)

 我把自己演哭了...

心酸.jpg

写了很多个版本的,包括数学公式暴力,快速幂TLE等等,最后想到了优化快速幂里的乘法,因为会爆longlong,但是和别人优化的效率简直是千差万别...?

  本题大意:

    给定三个longlongint范围内的正整数a, b, c,求出a^b mod c 的结果并输出。

  本题思路:

    见代码吧。

下面贴出我的各种版本的代码...

  参考代码:

//这道题数据有点水,不明白为啥数据里1^0 mod 1 == 1 ?魔鬼...

/*
    数学公式 :: 超时版 

#include <cstdio>
using namespace std;

typedef long long int LL;
LL a, b, mod, ans;

int main () {
    while(~scanf("%lld %lld %lld", &a, &b, &mod)) {
        ans = 1;
        for(int i = 1; i <= b; i ++) {
            ans = (ans * (a % mod)) % mod;
        }
        printf("%lld
", ans);
    }
    return 0;   
}
*/


/*
    快速幂::爆longlong版

#include <cstdio>
using namespace std;

typedef long long int LL;
LL a, b, c, ans;

void quickpow() {
    ans = 1;
    while(b) {
        if(b & 1)
            ans = (ans * (a % c)) % c;
            a = ((a % c) * (a % c)) % c;
            b >>= 1;
    }
}

int main() {
    while(~scanf("%lld %lld %lld", &a, &b, &c)) {
        quickpow();
        printf("%lld
", ans);
    }
}
*/

/*
    快速幂改进版 ::又来一发TLE版

#include <cstdio>
using namespace std;
typedef long long int LL;

LL quickpow(LL a, LL b, LL mod) {
    LL ans = 1;
    while(b) {//ans *= a;
        if(b & 1) {
            LL c = ans;
            for(int i = 2; i <= a; i ++)
                ans = (ans % mod + c % mod) % mod;
        }
        LL c = a;
        for(int i = 2; i <= c; i ++)
            a = (c % mod + a % mod) % mod;
        b >>= 1;
    }
    return ans;
}

int main () {
    LL ans, a, b, mod;
    while(~scanf("%I64d %I64d %I64d", &a, &b, &mod))
        printf("%I64d
", quickpow(a, b, mod));
    return 0;
}
*/

/* 快速幂与快速乘改进 ::AC版
*/
#include <cstdio>
using namespace std;

typedef long long int LL;

LL quickmuti(LL a, LL b, LL mod) {
    LL ret = 0;
    a %= mod;
    while(b) {
        if(b & 1) {
            ret += a;
            if(ret > mod) ret -= mod;
        }
        a <<= 1;
        if(a >= mod) a -= mod;
        b >>= 1;
    }
    return ret;
}

LL quickpow(LL a, LL b, LL mod) {
    LL ret = 1;
    while(b) {
        if(b & 1)   ret = quickmuti(ret, a, mod);
        a = quickmuti(a, a, mod);
        b >>= 1;
    }
    return ret;
}

int main () {
    LL a, b, mod;
    while(~scanf("%I64d %I64d %I64d", &a, &b, &mod)) {
        printf("%I64d
", quickpow(a, b, mod));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/bianjunting/p/10507621.html