After watching the master’s explanation, the theory is here: Fast Power Algorithm (the most detailed guide on the entire network to guide you to optimize step by step from scratch) - CSDN Blog
Example: Find the integer power raised by the integer base, and exponentiate the integer num_mod.
The python code is as follows:
import time
def normalPower(base, power, num_mod):
res = 1
for i in range(int(power)):
res = res * base % num_mod
return res
def fastPower(base, power, num_mod):
res = 1
while power > 0:
if power & 1: # 优化掉: power % 2 == 1
res = res * base % num_mod
power >>= 1 # 优化掉: power = power // 2
# base = (base * base) % num_mod
temp_base = base % num_mod
base = temp_base * temp_base % num_mod
return res
if __name__ == '__main__':
time1 = time.time()
print(fastPower(2, int(1e8), 1000))
print("fastPower Time:", round((time.time() - time1) * 1000, 5), 'ms')
time2 = time.time()
print(normalPower(2, int(1e8), 1000))
print("normalPower Time:", round((time.time() - time2) * 1000, 5), 'ms')
The output is as follows :
Let’s make the number a little bigger :
print(fastPower(int(1e200), int(1e100), 1000))
The time taken is still 0.0ms.
Let’s analyze it :
1. The first is matrix fast exponentiation. Compared with traditional methods, the speed-up effect is directly to the millisecond level.
2. "Bit operation" optimizes the operation of dividing by 2
power >>= 1 # Optimize: power = power // 2
3. The "AND operation" optimizes the even number judgment
if power & 1: # Optimize: power % 2 == 1
4. Here is my personal optimization, considering that the value of base may be very large.
# The following two lines optimize out base = (base * base) % num_mod
temp_base = base % num_mod
base = temp_base * temp_base % num_mod
After overall optimization, it is basically impossible to find a case with a time exceeding 0.0ms.