MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / modular_exponential

Function modular_exponential

maths/modular_exponential.py:11–32  ·  view source on GitHub ↗

>>> modular_exponential(5, 0, 10) 1 >>> modular_exponential(2, 8, 7) 4 >>> modular_exponential(3, -2, 9) -1

(base: int, power: int, mod: int)

Source from the content-addressed store, hash-verified

9
10
11def modular_exponential(base: int, power: int, mod: int):
12 """
13 >>> modular_exponential(5, 0, 10)
14 1
15 >>> modular_exponential(2, 8, 7)
16 4
17 >>> modular_exponential(3, -2, 9)
18 -1
19 """
20
21 if power < 0:
22 return -1
23 base %= mod
24 result = 1
25
26 while power > 0:
27 if power & 1:
28 result = (result * base) % mod
29 power = power >> 1
30 base = (base * base) % mod
31
32 return result
33
34
35def main():

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected