The power of rapid multiplication to tell us
- Fast exponentiation with respect to ordinary multiplication is very time complexity optimization, the reason is based on an algorithm operation position, the space complexity can be reduced to O (log N) level. And ordinary multiplication is O (N) level.
Let's look at the code:
#include<iostream>
using namespace std;
typedef long long ll;
ll Quick_Multi(ll a, ll b);
int main()
{
ll a, b;//a的b次幂
cout << "请输入a的几次方(a^b)" << endl;
cin >> a >> b;
cout << Quick_Multi(a, b) << endl;
return 0;
}
ll Quick_Multi(ll a, ll b)
{
ll ans = 1;
if (!a)//判断a是否为零,如若是0,返回0
return a;
while (b)
{
if (b & 1)//进行与一操作
ans *= a;
a *= a;
b >>= 1;//b向右移以为
}
return ans;
}
Code explanation
- First look at the function of power quickly. The function takes two parameters, a and b. a is a bottom, b is a power, the calculated result is a ^ b.
- In this code, and using the bitwise right shift. If for bit operations are not familiar with, you can look online searching.
- The basic idea: We have to end with a, b is power, then we have b split into a binary number. For example: 128 = 2 ^ 7; 3 We then split into a binary number, 0011, we will have 2 ^ (0011) ₂, i.e. becomes of (4 ^ 2) * (2 ^ 2) * (2 ^ 1) form.
- The split method is similar to divide and conquer. Using this method, the algorithm complexity is reduced from O (n) to the level of O (long n) level.
In general the idea, the party like we find 2 ^ 7, then the ordinary multiplication is 2 * 2 * 2 * 2 * 2 * 2 * 2 prayed seven times, but with the rapid multiplication of power, then we also had ( 2 * 2 * 2) * (2 * 2 * 2) = 2 * ((2 * 2 * 2) ^ 2) * 2, another point of view, multiplication by three times. In other words, we need to take to reduce multiplication to seven to three. This is the meaning fast exponentiation.