diff --git a/maths/modular_exponential.py b/maths/modular_exponential.py index 8715e1714..91fa0e462 100644 --- a/maths/modular_exponential.py +++ b/maths/modular_exponential.py @@ -1,8 +1,20 @@ -"""Modular Exponential.""" +""" + Modular Exponential. + Modular exponentiation is a type of exponentiation performed over a modulus. + For more explanation, please check https://en.wikipedia.org/wiki/Modular_exponentiation +""" +"""Calculate Modular Exponential.""" +def modular_exponential(base : int, power : int, mod : int): + """ + >>> modular_exponential(5, 0, 10) + 1 + >>> modular_exponential(2, 8, 7) + 4 + >>> modular_exponential(3, -2, 9) + -1 + """ -def modular_exponential(base, power, mod): - """Calculate Modular Exponential.""" if power < 0: return -1 base %= mod @@ -13,6 +25,7 @@ def modular_exponential(base, power, mod): result = (result * base) % mod power = power >> 1 base = (base * base) % mod + return result @@ -22,4 +35,8 @@ def main(): if __name__ == "__main__": + import doctest + + doctest.testmod() + main()