-
Notifications
You must be signed in to change notification settings - Fork 130
/
extended_euclidean.js
62 lines (48 loc) · 1.01 KB
/
extended_euclidean.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const floor = val => (val >= 0 || -1) * Math.floor(Math.abs(val));
/**
* The extended Euclidean algorithm is an algorithm to
* compute integers x and y such that given a and b.
* ax + by = gcd(a, b)
* @param {Number} a Coefficient of x
* @param {Number} b Coefficient of y
* @return {Object} Object containing value of x, y and gcd
*/
const extendedEuclidean = (a, b) => {
const terminate = 1;
let x = 1;
let y = 0;
let m = 0;
let n = 1;
if (a === 0) {
return { gcd: b, x: y, y: n };
}
if (b === 0) {
return { gcd: a, x, y: m };
}
let q;
let result = {
gcd: undefined,
x: undefined,
y: undefined
};
while (terminate) {
q = floor(a / b);
a %= b;
x -= q * y;
m -= q * n;
if (a === 0) {
result = { gcd: b, x: y, y: n };
break;
}
q = floor(b / a);
b %= a;
y -= q * x;
n -= q * m;
if (b === 0) {
result = { gcd: a, x, y: m };
break;
}
}
return result;
};
module.exports = extendedEuclidean;