-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5aded3a
commit 58f8824
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
def exp_modular(a: int, exponent: int, n: int) -> int: | ||
""" | ||
Modular exponentiation | ||
:param a: number to exponentiate | ||
:param exponent: exponent | ||
:param n: modulus | ||
:return: a^exponent (mod n) | ||
""" | ||
exp = int_2_base(exponent, 2) | ||
c = a | ||
for i in range(1, len(exp)): | ||
c = c * c % n | ||
if exp[i] == 1: | ||
c = c * a % n | ||
return c | ||
|
||
|
||
def int_2_base(a: int, base: int) -> list: | ||
""" | ||
Convert integer to base "base" | ||
:param a: integer to convert to big number form in base "base" | ||
:param base: base into which to convert integer "a" | ||
:return: bin number form in base "base" corresponding to "a" | ||
""" | ||
x = a | ||
reminders = [] | ||
while x != 0: | ||
q = x // base | ||
r = x % base | ||
x = q | ||
reminders.append(r) | ||
return reminders[::-1] |