概述
离散书中,出现了此算法。Recursive Modular Exponentiation,感觉还是挺快的,有点像二分查找法?
原理
ab mod c = (a mod c) * (b mod c)
对a^b mod c而言,
当b = 0时, a^0 mod c = 1 mod c = 1(base condition)
(当然,b = 1时作为基线条件也是可以的)
当b是偶数时,a ^ b mod c = (a^(b/2) * a^(b/2)) mod m
= (a^(b/2) mod m)^2 mod m
当b是奇数时,a ^ b mod c =(a ^ (b-1)) mod c * (a mod c)
.................................................偶数情况...........................
实现
#include <iostream>
#include <cmath>
using namespace std;
int power(int num)
{
return num * num;
}
int powerMod(int a, int b, int c)
{
if (a <= 0 || b < 0 || c <= 0)
return -1;
if (!b) return 1;
int ans = 1;
if (b % 2)
ans *= (a % c);
return (ans * power(powerMod(a, b/2, c)) % c);
}
int main(int argc, char const *argv[])
{
int a = 0, b = 0, c = 0;
cout << "Please enter a,b,c such that (a^b mod c):" << endl;
cin >> a >> b >> c;
cout << powerMod(a, b, c);
return 0;
}
新手练习,如有纰缪,欢迎指正。