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

Function binary_exp_mod_iterative

maths/binary_exponentiation.py:125–158  ·  view source on GitHub ↗

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

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

Source from the content-addressed store, hash-verified

123
124
125def binary_exp_mod_iterative(base: float, exponent: int, modulus: int) -> float:
126 """
127 Computes a^b % c iteratively, where a is the base, b is the exponent, and c is the
128 modulus
129
130 >>> binary_exp_mod_iterative(3, 4, 5)
131 1
132 >>> binary_exp_mod_iterative(11, 13, 7)
133 4
134 >>> binary_exp_mod_iterative(1.5, 4, 3)
135 2.0625
136 >>> binary_exp_mod_iterative(7, -1, 10)
137 Traceback (most recent call last):
138 ...
139 ValueError: Exponent must be a non-negative integer
140 >>> binary_exp_mod_iterative(7, 13, 0)
141 Traceback (most recent call last):
142 ...
143 ValueError: Modulus must be a positive integer
144 """
145 if exponent < 0:
146 raise ValueError("Exponent must be a non-negative integer")
147 if modulus <= 0:
148 raise ValueError("Modulus must be a positive integer")
149
150 res: int | float = 1
151 while exponent > 0:
152 if exponent & 1:
153 res = ((res % modulus) * (base % modulus)) % modulus
154
155 base *= base
156 exponent >>= 1
157
158 return res
159
160
161if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected