>>> modular_exponential(5, 0, 10) 1 >>> modular_exponential(2, 8, 7) 4 >>> modular_exponential(3, -2, 9) -1
(base: int, power: int, mod: int)
| 9 | |
| 10 | |
| 11 | def modular_exponential(base: int, power: int, mod: int): |
| 12 | """ |
| 13 | >>> modular_exponential(5, 0, 10) |
| 14 | 1 |
| 15 | >>> modular_exponential(2, 8, 7) |
| 16 | 4 |
| 17 | >>> modular_exponential(3, -2, 9) |
| 18 | -1 |
| 19 | """ |
| 20 | |
| 21 | if power < 0: |
| 22 | return -1 |
| 23 | base %= mod |
| 24 | result = 1 |
| 25 | |
| 26 | while power > 0: |
| 27 | if power & 1: |
| 28 | result = (result * base) % mod |
| 29 | power = power >> 1 |
| 30 | base = (base * base) % mod |
| 31 | |
| 32 | return result |
| 33 | |
| 34 | |
| 35 | def main(): |