[Algorithm analysis]-fast power algorithm

Assuming that a, b, and c are all positive integers, calculating the b power of a to modulo c is a very basic problem (a ^ b % c)in the asymmetric key algorithm RSA . Since it a,b,cmay be relatively large, direct calculation obviously cannot meet the efficiency requirements. Use the idea of ​​fast power to reduce the number of calculations.

The method is to discuss the situation according to the parity of b:

If b为偶数it may be setb = 2k , then

a ^ b % c  
= a ^ 2k % c  
= (a ^ k % c) * (a ^ k % c) % c  
= (a ^ k % c) ^ 2 % c

If b为奇数it may be setb = 2k + 1 , then

a ^ b % c  
= (a * a ^ 2k) % c  
= (a % c) * (a ^ 2k % c) % c  
= (a % c) * ((a ^ k % c) ^ 2 % c) % c

It can be seen that regardless of the parity, the calculation scale can be reduced to half of the original 时间复杂度由O(b)降至O(logb).

According to the above recursion formula, it is easy to write a recursive algorithm to solve this problem .

int powmod(int a, int b, int c) {
    
    
    if (0 == b) return 1;
    long long x = powmod(a, b/2, c);
    x = x * x % c;
    if (b & 1) x = x * a % c;
    return x;
}

If you change the implementation to iterative mode, this is how:

int powmod(int a, int b, int c) {
    
    
    long long x = 1, t = a;
    while (b) {
    
    
        if (b & 1) x = x * t % c;
        t = t * t % c;
        b /= 2;
    }
    return x;
}

Resource portal

  • Pay attention to [ Be a tender program ape ] public account
  • Reply to the [ python information ] [ 2020 Autumn Recruitment ] in the background of the [ Be a tender program ape ] public account to get the corresponding surprise!

「❤️ Thank you everyone」

  • Like to support it, so that more people can see this content (If you don’t like it, it’s all hooligans-_-)
  • Welcome to share your thoughts with me in the message area, and you are also welcome to record your thought process in the message area.

Guess you like

Origin blog.csdn.net/ywsydwsbn/article/details/109269881