@ashenm/

Smallest Common Multiple

JavaScript

Specimen code solution for freeCodeCamp advanced algorithm scripting challenge.

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
 * Smallest Common Multiple
 * https://www.freecodecamp.org/challenges/smallest-common-multiple
 * Returns LCM of all sequential numbers in a given range
 *
 * Ashen Gunaratne
 * [email protected]
 *
 */

function smallestCommons(arr) {

  // range
  let min = Math.min.apply(null, arr);
  let max = Math.max.apply(null, arr);

  let smallestCommon = lcm(min, min + 1);

  while(min < max) {
    min++;
    smallestCommon = lcm(smallestCommon, min);
  }

  return smallestCommon;
}


/**
 * Calculates Greatest Common Divisor
 * of two nubers using Euclidean algorithm
 */
function gcd(a, b) {
  while (b > 0) {
    let tmp = a;
    a = b;
    b = tmp % b;
  }
  return a;
}


/**
 * Calculates Least Common Multiple
 * for two numbers utilising GCD
 */
function lcm(a, b) {
  return (a * b / gcd(a, b));
}


// test here
smallestCommons([1,5]);
Native Browser JavaScript