Calculating pow(a,b) mod n

后端 未结 14 1225
执念已碎
执念已碎 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:06

    In order to calculate pow(a,b) % n to be used for RSA decryption, the best algorithm I came across is Primality Testing 1) which is as follows:

     int modulo(int a, int b, int n){
        long long x=1, y=a; 
        while (b > 0) {
            if (b%2 == 1) {
                x = (x*y) % n; // multiplying with base
            }
            y = (y*y) % n; // squaring the base
            b /= 2;
        }
        return x % n;
    }
    

    See below reference for more details.


    1) Primality Testing : Non-deterministic Algorithms – topcoder

提交回复
热议问题