Design & Download
Your JS Library
in Seconds!!!

Snippet: Greatest Common Denominator & Least Common Multiple

Written by Christopher West (cwest) on December 05, 2015.
Find the greatest common divisor and the least common multiple of two integers quickly and simply.
function gcd(int1, int2) {
  return int2 ? gcd(int2, int1 % int2) : int1;
}

function lcm(int1, int2) {
  return Math.abs(int1 * int2) / gcd(int1, int2);
}

gcd(...) API Documentation

Description

Finds the largest integer which evenly divides the two specified integers.

Parameters

  1. int1 {number}:
    The first of two integers for which the greatest common denominator should be found.
  2. int2 {number}:
    The second of two integers for which the greatest common denominator should be found.

Returns

Returns the largest integer which evenly divides int1 and int2.

lcm(...) API Documentation

Description

Finds the smallest integer that is evenly divisible by the two specified integers.

Parameters

  1. int1 {number}:
    The first of two integers that must be evenly divisible by the returned least common multiple.
  2. int2 {number}:
    The second of two integers that must be evenly divisible by the returned least common multiple.

Returns

Returns the smallest integer that is evenly divisible by int1 and int2.