码迷,mamicode.com
首页 > 其他好文 > 详细

快速幂 和 快速乘

时间:2019-05-12 13:49:12      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:utc   def   putc   using   ons   put   class   std   inf   

#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;
}

 

快速幂 和 快速乘

标签:utc   def   putc   using   ons   put   class   std   inf   

原文地址:https://www.cnblogs.com/AK-ls/p/10851920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!