I want to calculate ab mod n for use in RSA decryption. My code (below) returns incorrect answers. What is wrong with it?
unsigned long i
Here is another way. Remember that when we find modulo multiplicative inverse
of a
under mod m
.
Then
a and m must be
coprime
with each other.
We can use gcd extended
for calculating modulo multiplicative inverse
.
For computing ab mod m when a
and b
can have more than 105 digits then its tricky to compute the result.
Below code will do the computing part :
#include
#include
using namespace std;
/*
* May this code live long.
*/
long pow(string,string,long long);
long pow(long long ,long long ,long long);
int main() {
string _num,_pow;
long long _mod;
cin>>_num>>_pow>>_mod;
//cout<<_num<<" "<<_pow<<" "<<_mod<0){
if((p&1)==0){
p/=2;
a=(a*a)%mod;
}
else{
p--;
res=(res*a)%mod;
}
}
return res;
}
This code works because ab mod m can be written as (a mod m)b mod m-1 mod m.
Hope it helped { :)