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)
| 123 | |
| 124 | |
| 125 | def 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 | |
| 161 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected