Skip to content

Commit 691172d

Browse files
authored
Merge pull request prakhar1989#44 from manishrw/master
ADDED modular exponentiation in misc
2 parents df48982 + 385d753 commit 691172d

File tree

4 files changed

+40
-0
lines changed

4 files changed

+40
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ Completed
4242
- String Reverse
4343
- Parenthesis Matching
4444
- Infix to Postfix
45+
- Modular exponentiation
4546

4647

4748
Tests
@@ -52,3 +53,4 @@ Tests
5253
python -m tests.heap_test
5354
python -m tests.unionfind_test
5455
python -m tests.singly_linked_list_test
56+
python -m tests.modular_exponentiation_test

misc/__init__.py

Whitespace-only changes.

misc/modular_exponentiation.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"""
2+
Problem: https://en.wikipedia.org/wiki/Modular_exponentiation
3+
"""
4+
5+
def modular_exponentiation(base, exp, mod):
6+
if exp < 1:
7+
raise ValueError("Exponentiation should be ve+ int")
8+
if mod == 1:
9+
return 0
10+
elif mod < 1:
11+
raise ValueError("Modulus should be ve+ int")
12+
#Initialize result to 1
13+
result = 1
14+
base %= mod
15+
while exp > 0:
16+
#multiply base to result if exp is odd
17+
if exp % 2 == 1:
18+
result = (result * base) % mod
19+
#Double base and half exp
20+
exp = exp >> 1
21+
base = (base ** 2) % mod
22+
return result
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import os, sys
2+
import unittest
3+
sys.path.append(os.path.join(os.getcwd(), os.path.pardir))
4+
from misc import modular_exponentiation as me
5+
6+
class TestLCS(unittest.TestCase):
7+
def test_modular_exponentiation(self):
8+
self.assertEqual(me.modular_exponentiation(2, 10, 100), 24)
9+
self.assertEqual(me.modular_exponentiation(2, 200, 10), 6)
10+
self.assertEqual(me.modular_exponentiation(5, 20, 1), 0)
11+
#self.assertEqual(me.modular_exponentiation(8, 1, 10), 8)
12+
self.assertRaises(ValueError, me.modular_exponentiation, 12, -1, 10)
13+
self.assertRaises(ValueError, me.modular_exponentiation, 12, 5, 0)
14+
15+
if __name__ == "__main__":
16+
unittest.main()

0 commit comments

Comments
 (0)