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)
| 88 | |
| 89 | |
| 90 | def 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 | |
| 125 | def binary_exp_mod_iterative(base: float, exponent: int, modulus: int) -> float: |
nothing calls this directly
no outgoing calls
no test coverage detected