指数幂求模
comupte aj mod p
Formular
(pq) mod N = ((p mod N)*(q mod N)) mod N
at={a(aj/2)2(aj/2)2j is odd numberj is even number
Code Implementation
#include
#include
using namespace std;
int modular_exponent_re(int a,int j, int p){
if(p<0){
return -1;
}
if(j==0){
return 1;
}else{
int z = modular_exponent_re(a, j/2, p);
if(j%2==0){
return ((z%p)*(z%p))%p;
}else{
return (a*(z%p)*(z%p))%p;
}
}
}
int modular_exponent(int a,int j,int p){
if(j<0){
return -1;
}
if(j==0){
return 1;
}else{
stack<int> s;
int result = a;
while(j){
s.push(j);
j=j/2;
}
while (s.size()>1) {
int t = s.top();
s.pop();
result = ((result%p)*(result%p))%p;
if (s.empty()) {
break;
}
if (t*2 != s.top()) {
result = ((a%p)*result)%p;
}
}
return result;
}
}
int modular_exponent1(int a,int j,int p){
if(j<0){
return -1;
}
if(j==0){
return 1;
}else{
int result = 1;
while (j>0) {
if (j%2!=0) {
result = (a*result)%p;
}
a = a%p;
a=(a*a)%p;
j=j/2;
}
return result;
}
}
s=1
if j is odd s=s*a
(a2)j/2
int modular_exponent_trick(int a,int j,int p){
int s = 1;
while(j){
if (j%2 != 0) {
s = (s*a)%p;
}
a = (a*a)%p;
j=j/2;
}
return s;
}
int main(int argc, const char * argv[]) {
std::cout << "Hello, World!
";
std::cout << modular_exponent_re(3, 10, 31)<<endl;
std::cout << modular_exponent(3, 10, 31)<<endl;
std::cout << modular_exponent_trick(3, 10, 31)<<endl;
return 0;
}