Calculating pow(a,b) mod n

后端 未结 14 1138
执念已碎
执念已碎 2020-11-22 16:25

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         


        
14条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 17:18

    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 { :)

提交回复
热议问题