GENEVE

我还想继续玩c++

导航

又是一个赤裸裸的模板,倍增思想其实是关键,我们只有稍加改动,也可以得出另外一种运算,快速乘,但实用性不如快速幂,大概只有在大整数乘法时才会用到

而倍增思想并不是仅仅用于快速运算,倍增求lca也是常用的倍增算法

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>

using namespace std;

typedef long long ll;

ll fast_power(ll,ll,ll); // 求 a^b % c 

int main(){
    ll a,b,c;
    scanf("%lld%lld%lld",&a,&b,&c);
    printf("%lld",fast_power(a,b,c));
    return 0;
}
ll fast_power(ll a,ll b,ll c){
    ll ans=1;
    // 倍增思想求快速幂 
    while (b
){
        if (b & 1)
            ans = ans * a % c; 
        else ans %= c;
        b >>= 1;
        a = a * a % c; 
    }
    return ans;
}
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>

using namespace std;

typedef long long ll;

ll fast_calc(ll,ll,ll);

int main(){
    ll a,b,c;
    scanf("%lld%lld%lld",&a,&b,&c);
    printf("%lld",fast_calc(a,b,c)); 
    return 0;
}

ll fast_calc(ll x,ll y,ll z){
    ll ans = 0;
    while (y){
        if (y & 1){
            ans += x;
            ans %= z;
        }
        x <<= 1;
        x %= z;
        y >>= 1;
    }
    return ans;
}