Calculating using multiplications instead of

The idea is splitting the work using the binary representation of the exponent, the algorithm main idea is simple, it’s built on top of .

example:

Note

 An element in the sequence is just the square of the previous element

the point is that, calculate then check the x’s bit is set or not i.e. take a^x or leave it.

def bin_exp(a: int, n: int, mod: int):
	 res = 1
	 a = a % mod
	 while n:
		 if n & 1 == 1: # take it
			res = res * a % mod
		# calculate the next item
		# you start with a**1 then calculate a**2 and so on
		a = a * a % mod
		n >>= 1
	return res