MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / binary_exp_mod_recursive

Function binary_exp_mod_recursive

maths/binary_exponentiation.py:90–122  ·  view source on GitHub ↗

Computes a^b % c recursively, where a is the base, b is the exponent, and c is the modulus >>> binary_exp_mod_recursive(3, 4, 5) 1 >>> binary_exp_mod_recursive(11, 13, 7) 4 >>> binary_exp_mod_recursive(1.5, 4, 3) 2.0625 >>> binary_exp_mod_recursive(7, -1, 10)

(base: float, exponent: int, modulus: int)

Source from the content-addressed store, hash-verified

88
89
90def binary_exp_mod_recursive(base: float, exponent: int, modulus: int) -> float:
91 """
92 Computes a^b % c recursively, where a is the base, b is the exponent, and c is the
93 modulus
94
95 >>> binary_exp_mod_recursive(3, 4, 5)
96 1
97 >>> binary_exp_mod_recursive(11, 13, 7)
98 4
99 >>> binary_exp_mod_recursive(1.5, 4, 3)
100 2.0625
101 >>> binary_exp_mod_recursive(7, -1, 10)
102 Traceback (most recent call last):
103 ...
104 ValueError: Exponent must be a non-negative integer
105 >>> binary_exp_mod_recursive(7, 13, 0)
106 Traceback (most recent call last):
107 ...
108 ValueError: Modulus must be a positive integer
109 """
110 if exponent < 0:
111 raise ValueError("Exponent must be a non-negative integer")
112 if modulus <= 0:
113 raise ValueError("Modulus must be a positive integer")
114
115 if exponent == 0:
116 return 1
117
118 if exponent % 2 == 1:
119 return (binary_exp_mod_recursive(base, exponent - 1, modulus) * base) % modulus
120
121 r = binary_exp_mod_recursive(base, exponent // 2, modulus)
122 return (r * r) % modulus
123
124
125def binary_exp_mod_iterative(base: float, exponent: int, modulus: int) -> float:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected