typescript-algorithms-and-datastructures
Version:
Useful algorithms and Data structures written in typescript.
63 lines • 2.17 kB
JavaScript
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function extendedEuclidesAlgorithm(a, b) {
if (!Number.isInteger(a) || !Number.isInteger(b)) {
throw new Error("Euclide's extended algorithm works only for positive integers");
}
if (a === 0 && b === 0) {
throw new Error("Euclide's extended algorithm works only for positive integers");
}
const aSign = a < 0 ? -1 : 1;
const bSign = b < 0 ? -1 : 1;
a = Math.abs(a);
b = Math.abs(b);
if (a === b) {
return {
gcd: a,
x: 1,
y: 0
};
}
else if (a < b) {
const result = extendedEuclidesAlgorithmInternal(b, a);
return {
gcd: result.gcd,
x: result.y * aSign,
y: result.x * bSign
};
}
else {
const result = extendedEuclidesAlgorithmInternal(a, b);
return {
gcd: result.gcd,
x: result.x * aSign,
y: result.y * bSign
};
}
}
exports.extendedEuclidesAlgorithm = extendedEuclidesAlgorithm;
function extendedEuclidesAlgorithmInternal(a, b) {
const result = {
gcd: a,
x: 1,
y: 0
};
if (b !== 0) {
const recursiveResult = extendedEuclidesAlgorithmInternal(b, a % b);
result.gcd = recursiveResult.gcd;
result.x = recursiveResult.y;
result.y = recursiveResult.x - recursiveResult.y * Math.floor(a / b);
}
return result;
}
});
//# sourceMappingURL=extendedEuclidesAlgorithm.js.map