第五輯 數論數學
- 最大公約數
(gcd)
- 擴展
Euclidean
- 快速冪
GCD (Greatest Common Divisor)
1 | int Gcd(int a, int b) |
Ex-GCD (Extended Euclidean)
1 |
|
Binary Exponentiation
其實是二進制取冪,也稱平方法。
zzj
提供的非遞歸方案 (mod p
意義下取冪)C++ 1
2
3
4
5
6
7
8
9
10
11int quick_power(int a, int b, int p)
{
int ans = 1;
while(b)
{
if(b&1) ans = ans*a%p;
a = a*a%p;
b >>= 1;
}
return ans;
}OI-Wiki
1上的遞歸實現C++ 1
2
3
4
5
6
7
8long long binpow(long long a, long long b) {
if (b == 0) return 1;
long long res = binpow(a, b / 2);
if (b % 2)
return res * res * a;
else
return res * res;
}OI-Wiki
上的非遞歸實現C++ 1
2
3
4
5
6
7
8
9long long binpow(long long a, long long b) {
long long res = 1;
while (b > 0) {
if (b & 1) res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
References
1. OI-Wiki
章節 快速冪 ↩