Taka's Library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub Taka0007/Library

:heavy_check_mark: 繰り返し二乗法(C++)
(num_theory/pow.cpp)

概要

繰り返し二乗法を行います。

計算量

補足

Pythonなら下記コードで自動的に繰り返し二乗法を行ってくれる。 $a^b$を $mod$ で割った余りを $O(log(b))$ で出してくれる。

pow(a,b,mod)

Verified with

Code

#include <iostream>
using namespace std;

const long long MOD = 1000000007;  // 10^9 + 7

long long mod_pow(long long base, long long exp, long long mod) {
    long long result = 1;
    while (exp > 0) {
        if (exp % 2 == 1) {
            result = (result * base) % mod;
        }
        base = (base * base) % mod;
        exp /= 2;
    }
    return result;
}
#line 1 "num_theory/pow.cpp"
#include <iostream>
using namespace std;

const long long MOD = 1000000007;  // 10^9 + 7

long long mod_pow(long long base, long long exp, long long mod) {
    long long result = 1;
    while (exp > 0) {
        if (exp % 2 == 1) {
            result = (result * base) % mod;
        }
        base = (base * base) % mod;
        exp /= 2;
    }
    return result;
}
Back to top page