- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodexp.py
More file actions
Latest commit
37 lines (30 loc) · 765 Bytes
/
Copy pathmodexp.py
File metadata and controls
37 lines (30 loc) · 765 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
"""
Task:
Compute Modular exponentiation, which is a type of exponentiation performed
over a modulus.
See: https://www.wikiwand.com/en/Modular_exponentiation
>>> mod_pow(4, 13, 497)
445
>>> mod_pow(3, 1000, 7)
4
>>> mod_pow(7, 107, 9) == pow(7, 107, 9)
True
"""
# Solution 1
defmod_pow(base, exponent, modulus):
result=1
for_inrange(1, exponent+1):
result= (result*base) %modulus
returnresult
# Solution 2
defmod_pow(base, exponent, modulus):
result=1
whileexponent>0:
ifexponent%2:
result= (result*base) %modulus
base= (base*base) %modulus
exponent=exponent//2
returnresult
if__name__=='__main__':
importdoctest
doctest.testmod()