UNPKG

@woosh/meep-engine

Version:

Pure JavaScript game engine. Fully featured and production ready.

56 lines (43 loc) 1.19 kB
import { assert } from "../assert.js"; import { min2 } from "./min2.js"; import { max2 } from "./max2.js"; /** * Find the greatest common divisor (denominator/factor) * @param {number} a * @param {number} b * @returns {number} */ function computeGreatestCommonDivisor_Naive(a, b) { assert.isNumber(a, 'a'); assert.isNumber(b, 'b'); // start with the lowest of the two as a guess let result = min2(a, b); while (result > 1) { if (a % result === 0 && b % result === 0) { // found a common divisor break; } // keep going down result--; } return result; } /** * @see https://en.wikipedia.org/wiki/Euclidean_algorithm * @param {number} a * @param {number} b * @returns {number} */ function computeGreatestCommonDivisor_Euclid(a, b) { assert.isNumber(a, 'a'); assert.isNumber(b, 'b'); let _a = max2(a, b); let _b = min2(a, b); while (_b !== 0) { const t = _b; _b = _a % _b; _a = t; } return _a; } export const computeGreatestCommonDivisor = computeGreatestCommonDivisor_Euclid;