Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Sep 7, 2025. It is now read-only.
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)}`);