Something is wrong in my code for modular exponentiation and I can't spot the problem despite of writing it three times when using two different sources of pseudocode. I've read other questions about modular exponentiation in C++ on SE but that didn't help me. Here is my last code, written by simpler but less optimal way I think :
#include<iostream>
using namespace std;
// base ^ exponent mod modulus
unsigned mulmod1(unsigned base, unsigned exponent, unsigned modulus) {
int result = 1;
while(exponent > 0){
if(exponent % 2 == 1)
result = (result * base) % modulus;
exponent >>= 1;
base = (base * base) % modulus;
}
return result;
}
int main(){
//9688563^45896 mod 71 = 30
//12^53 mod 7 = 3
cout<<mulmod1(9688563,45896 ,71)<<"\n"; //gives 10 instead of 30
cout<<mulmod1(12,53,7)<<"\n"; //gives correct answer 3
return 0;
}