Fast power algorithm C++

A simple example to quickly understand

To calculate 2 raised to the 13th power, first, we convert the exponent 13 into binary form, which gives us 1101.

Then, we iterate through each bit from right to left:

  • The first digit is 1, so we multiply the result by 2 to the 20 power = 2 to the 1st power = 2;
  • The second bit is 0, so we don't need to multiply anything;
  • The third digit is 1, so we multiply the result by 2 to the 22 power = 2 to the 4th power = 16;
  • The fourth digit is 1, so we multiply the result by 2 to the 23 power = 2 to the 8th power = 256.

Therefore, 2 to the 13th power = 2×16×256=8192.

Example code

Find 2**2023%1000, which is the remainder of 2 raised to the power of 2023 divided by 1000.
Answer submission
  This is a fill-in-the-blank question. You only need to calculate the result and submit it. The result of this question is an integer. Only fill in this integer when submitting the answer. No points will be awarded if you fill in excess content.

#include<iostream>
using namespace std;

int fastPower(int base, int power, int mod) {
    
    
    int result = 1;
    while (power > 0) {
    
    
        if (power & 1) {
    
    
            result = (result * base) % mod;
        }
        base = (base * base) % mod;
        power >>= 1;
    }
    return result;
}

int main() {
    
    
    cout << fastPower(2, 2023, 1000);
    return 0;
}

In the above C++ code, the fastPower function implements this algorithm.
  It accepts three parameters: base, exponent power and modulus mod.
  In the function body, it first initializes the result to 1, and then enters a loop. The loop condition is power > 0. In each round of the loop, it first checks whether the lowest bit of power is 1. If so, it multiplies the result by base and modulo mod; then, regardless of whether the lowest bit of power is 1, it squares base itself and takes the modulo modulo. Mod, and shift the power one position to the right. In this way, when power becomes 0, the loop ends, and the result is the result of 2 raised to the power of 2023 modulo 1000. This is the implementation of the fast power algorithm.

Guess you like

Origin blog.csdn.net/qq_63250901/article/details/134646700