(arg1, arg2)
| 25 | * @returns Array with GCD and first and second Bézout coefficients |
| 26 | */ |
| 27 | const extendedEuclideanGCD = (arg1, arg2) => { |
| 28 | if (typeof arg1 !== 'number' || typeof arg2 !== 'number') |
| 29 | throw new TypeError('Not a Number') |
| 30 | if (arg1 < 1 || arg2 < 1) throw new TypeError('Must be positive numbers') |
| 31 | |
| 32 | // Make the order of coefficients correct, as the algorithm assumes r0 > r1 |
| 33 | if (arg1 < arg2) { |
| 34 | const res = extendedEuclideanGCD(arg2, arg1) |
| 35 | const temp = res[1] |
| 36 | res[1] = res[2] |
| 37 | res[2] = temp |
| 38 | return res |
| 39 | } |
| 40 | |
| 41 | // At this point arg1 > arg2 |
| 42 | |
| 43 | // Remainder values |
| 44 | let r0 = arg1 |
| 45 | let r1 = arg2 |
| 46 | |
| 47 | // Coefficient1 values |
| 48 | let s0 = 1 |
| 49 | let s1 = 0 |
| 50 | |
| 51 | // Coefficient 2 values |
| 52 | let t0 = 0 |
| 53 | let t1 = 1 |
| 54 | |
| 55 | while (r1 !== 0) { |
| 56 | const q = Math.floor(r0 / r1) |
| 57 | |
| 58 | const r2 = r0 - r1 * q |
| 59 | const s2 = s0 - s1 * q |
| 60 | const t2 = t0 - t1 * q |
| 61 | |
| 62 | r0 = r1 |
| 63 | r1 = r2 |
| 64 | s0 = s1 |
| 65 | s1 = s2 |
| 66 | t0 = t1 |
| 67 | t1 = t2 |
| 68 | } |
| 69 | return [r0, s0, t0] |
| 70 | } |
| 71 | |
| 72 | export { extendedEuclideanGCD } |
no outgoing calls
no test coverage detected