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

Update gcd.js #68

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
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
32 changes: 23 additions & 9 deletions algorithms/math/gcd.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
// GCD - greatest common divisor or HCF - highest common factor
"use strict";

function gcd (small, large) {
if (small === 0) { return large } else { return gcd(large % small, small) }
}
/** @typedef {number|bigint} numeric */

const gcdList = [[6, 9], [6, 12], [12, 18], [7, 14], [7, 13]]
/** @param {numeric} x */
const abs = x => x < 0 ? -x : x;

for (const set of gcdList) {
const small = set[0]
const large = set[1]
console.log(`GCD for ${small} and ${large} is ${gcd(small, large)}`)
/**
* GCD - greatest common divisor or HCF - highest common factor.
* Using the Euclidean algorithm (not to be confused with Euclid's algo, which does subtraction).
*
* Argument order doesn't matter.
* `return`s correct results even for non-integers (sometimes, because of rounding errors).
* This fn is 2-adic, the variadic implementation is left as an exercise to the reader.
* @param {numeric} a
* @param {numeric} b
*/
const gcd = (a, b) => {
while (b != 0)
[a, b] = [b, a % b];
return abs(a)
}

const tuples = [[6, 9], [6, 12], [-12, -18], [7, 14], [7, 13], [1/2, 2]];

for (const [a, b] of tuples)
console.log(`GCD of ${a} and ${b} is ${gcd(a, b)}`);