Skip to content

Commit a484b2d

Browse files
Added a useful script to compute modular exponentiation.
1 parent 479f330 commit a484b2d

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Iterative Python3 program
2+
# to compute modular power
3+
4+
# Iterative Function to calculate
5+
# (x^y)%p in O(log y)
6+
def power(x, y, p) :
7+
res = 1 # Initialize result
8+
9+
# Update x if it is more
10+
# than or equal to p
11+
x = x % p
12+
13+
while (y > 0) :
14+
15+
# If y is odd, multiply
16+
# x with result
17+
if ((y & 1) == 1) :
18+
res = (res * x) % p
19+
20+
# y must be even now
21+
y = y >> 1 # y = y/2
22+
x = (x * x) % p
23+
24+
return res
25+
26+
27+
# Driver Code
28+
29+
x = 2; y = 5; p = 13
30+
print("Power is ", power(x, y, p))

0 commit comments

Comments
 (0)