[剑指 offer] JT12---The integer power of the value (to throw a brick and inspire us to talk about the [fast power] algorithm!)

The topic is as follows

Insert picture description here

Topic analysis

direct pow(base,exponent)You can get rid of this question,
but it is meaningless.
The test point for this question should be how to calculate when the exponent is negative. If the mathematics is okay, this question is still very simple. Of course, we will think about the power problem quickly. power. In a later blog, we will introduce fast power

Let’s take a look at ordinary direct powers

class Solution {
    
    
public:
    double Power(double base, int exponent) {
    
    
        double a=1.0;
        if(base==0) return 0;
        if(exponent==0) return 1;
        if(exponent<0) base=1.0/base;
        while(exponent){
    
    
            a*=base;
            exponent=(exponent>0)?(--exponent):(++exponent);
        }
        return a;
    }
};

Insert picture description here

Let's take a look at what is fast power

In fact, fast exponentiation is very similar to synthesizing big watermelon

The students should have played the synthetic big watermelon, that is, two small melons can be combined into a more powerful melon, that is, 1+1==capital 1, which is even more stubborn.
So why can't exponentiation be like this?
Why don't I just multiply a quadratic?
Why don't I just multiply the quadratic by two times?

Some students may find it a bit interesting, so let's take a look at the template of quick power, the explanation is in the comments

For example,
32=2 * 2 * 2 * 2 *2; 32 is equal to the fifth power of 2 and
5 converted into binary is 1001;
so32 can be converted into the fourth power of 2 times the power of 2
In this way, the number of multiplications is reduced, and the calculation time is greatly reduced when a large power is reached.

long long fastPower(long long base, long long power) {
    
    
    long long result = 1;
    while (power > 0) {
    
    
        if (power & 1) {
    
    //此处等价于if(power%2==1)
            result = result * base % 1000;
        }
        power >>= 1;//此处等价于power=power/2
        base = (base * base) % 1000;
    }
    return result;
}

Here is the optimization of the fast power template
applied to the above as follows

class Solution {
    
    
public:
    double Power(double base, int exponent) {
    
    
        double a=1.0;
        if(base==0) return 0;
        if(exponent==0) return 1;
        if(exponent<0) {
    
    
            base=1.0/base;
            exponent*=(-1);
        }
        while(exponent){
    
    
            if(exponent&1){
    
    
                a=a*base;
            }
            exponent>>=1;
            base*=base;
        }
        return a;
    }
};

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/114363191