Modular Division : An efficient algorithm for dividing b by a modulo n. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should return an integer x such that 0≤x≤n-1, and b/a=x(modn)
(a: int, b: int, n: int)
| 2 | |
| 3 | |
| 4 | def modular_division(a: int, b: int, n: int) -> int: |
| 5 | """ |
| 6 | Modular Division : |
| 7 | An efficient algorithm for dividing b by a modulo n. |
| 8 | |
| 9 | GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) |
| 10 | |
| 11 | Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should |
| 12 | return an integer x such that 0≤x≤n-1, and b/a=x(modn) (that is, b=ax(modn)). |
| 13 | |
| 14 | Theorem: |
| 15 | a has a multiplicative inverse modulo n iff gcd(a,n) = 1 |
| 16 | |
| 17 | |
| 18 | This find x = b*a^(-1) mod n |
| 19 | Uses ExtendedEuclid to find the inverse of a |
| 20 | |
| 21 | >>> modular_division(4,8,5) |
| 22 | 2 |
| 23 | |
| 24 | >>> modular_division(3,8,5) |
| 25 | 1 |
| 26 | |
| 27 | >>> modular_division(4, 11, 5) |
| 28 | 4 |
| 29 | |
| 30 | """ |
| 31 | if n <= 1: |
| 32 | raise ValueError("Modulus n must be greater than 1") |
| 33 | if a <= 0: |
| 34 | raise ValueError("Divisor a must be a positive integer") |
| 35 | if greatest_common_divisor(a, n) != 1: |
| 36 | raise ValueError("a and n must be coprime (gcd(a, n) = 1)") |
| 37 | |
| 38 | (_d, _t, s) = extended_gcd(n, a) # Implemented below |
| 39 | x = (b * s) % n |
| 40 | return x |
| 41 | |
| 42 | |
| 43 | def invert_modulo(a: int, n: int) -> int: |
nothing calls this directly
no test coverage detected