Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active December 8, 2023 09:16
Show Gist options
  • Save mmyoji/b383e788d1fe0f04851e969e5559a0f3 to your computer and use it in GitHub Desktop.
Save mmyoji/b383e788d1fe0f04851e969e5559a0f3 to your computer and use it in GitHub Desktop.
LCM & GCD in TypeScript
/**
* LCM ... Least Common Multiple (最小公倍数)
* GCD ... Greatest Common Divisor (最大公約数)
*
* LCM = (A * B) / GCD
*/
function _findGCD(a: number, b: number): number {
if (a === 0) return b;
if (b === 0) return a;
return _findGCD(b, a % b);
}
export function findGCD(a: number, b: number): number {
const [big, small] = a > b ? [a, b] : [b, a];
return _findGCD(big, small);
}
export function findGCDs([first, ...rest]: number[]): number {
if (first == null) return 0;
return rest.reduce((acc, n) => findGCD(acc, n), first);
}
export function findLCM(a: number, b: number): number {
if (a === 0 || b === 0) {
return 0;
}
return a * b / findGCD(a, b);
}
export function findLCMs([first, ...rest]: number[]): number {
if (first == null) return 0;
return rest.reduce((acc, n) => findLCM(acc, n), first);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment