快速幂 和 快速乘

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 5e5 + 100;
const int MAXM = 3e3 + 10;

template < typename T > inline void read(T &x) {
    x = 0; T ff = 1, ch = getchar();
    while(!isdigit(ch)) {
        if(ch == '-') ff = -1;
        ch = getchar();
    }
    while(isdigit(ch)) {
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    x *= ff;
}

template < typename T > inline void write(T x) {
    if(x < 0) putchar('-'), x = -x;
    if(x > 9) write(x / 10);
    putchar(x % 10 + '0');
} 

ll a, b, p;

int power(int a, int b, int p) {
    int ans = 1 % p;
    while(b) {
        if(b & 1) ans = (ll) ans * a % p;
        a = (ll) a * a % p;
        b >>= 1;
    }
    return ans;
}

ll mul(ll a, ll b, ll p) {
    ll ans = 0;
    while(b) {
        if(b & 1) ans = (ans + a) % p;
        a = a * 2 % p;
        b >>= 1;
    }
    return ans;
}

int main() {
    read(a); read(b); read(p);
    write(power(a, b, p));
    write(mul(a, b, p));
    return 0;
}

 

posted @ 2019-05-12 13:06  海边微风起  阅读(158)  评论(0编辑  收藏  举报