Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extended Euclidean Algorithm #200

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Added Extended Euclidean Algorithm
amitsingh19975 committed Sep 4, 2018
commit 449e6fcdc79bdf6247c1619582336022e8a594a7
14 changes: 14 additions & 0 deletions src/algorithms/math/extended-euclidean-algorithm/README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Extended Euclidean algorithm

In arithmetic and computer programming, the extended Euclidean algorithm is an extension to the Euclidean algorithm,
and computes, in addition to the greatest common divisor of integers a and b, also the coefficients of Bézout's
identity, which are integers x and y such that `ax + by = gcd(a,b)`.
This is a certifying algorithm, because the gcd is the only number that can simultaneously satisfy this equation and
divide the inputs. It allows one to compute also, with almost no extra cost, the quotients of a and b by their
greatest common divisor.

![Extended](https://i.stack.imgur.com/UiQ2m.png)

## References

[Wikipedia](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm)
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import extendedEuclid from '../extendedEuclid';

describe('extendedEuclideanAlgorithm', () => {
it('should calculate coefficients', () => {
expect(extendedEuclid(30, 20)).toEqual({
gcd: 10,
x: 1,
y: -1,
});

expect(extendedEuclid(30, 50)).toEqual({
gcd: 10,
x: 2,
y: -1,
});

expect(extendedEuclid(65, 40)).toEqual({
gcd: 5,
x: -3,
y: 5,
});
});
});
21 changes: 21 additions & 0 deletions src/algorithms/math/extended-euclidean-algorithm/extendedEuclid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @param {number} Coefficient A
* @param {number} Coefficient B
* @return {Object} {gcd, x, y}
*/

export default function extendedEuclid(coeffA, coeffB) {
if (coeffA === 0) {
return {
gcd: coeffB,
x: 0,
y: 1,
};
}
const variables = extendedEuclid(coeffB % coeffA, coeffA);
return {
gcd: variables.gcd,
x: (variables.y - Math.floor(coeffB / coeffA) * variables.x),
y: variables.x,
};
}