ja / en
Overview

繰り返し二乗法

2024/07/29
1 min read

Purpose

Calculates an  (mod  mod)a^n \ \ (\text{mod}\ \ mod) in O(log(n))O(\log(n)).

Time Complexity

O(logn)O(\log n)

Usage

mop(a,b,mod) returns an  (mod  mod)a^n \ \ (\text{mod}\ \ mod).

Implementation

int mop(int a, int n, int mod = LLONG_MAX) {
int res = 1;
while (n > 0) {
if (n & 1)
res = res * a % mod;
a = a * a % mod;
n >>= 1;
}
return res;
}

Verify

//TODO