Randell Dawson d78168f7db fix(curriculum): Remove unnecessary assert message argument from English challenges JavaScript Algorithms and Data Structures - 03 (#36403)
* fix: rm assert msg basic-data-structures

* fix: rm assert msg intermed-algo-scripting

* fix: rm assert msg data-structures projects
2019-07-24 10:56:38 +02:00

2.3 KiB

id, title, isRequired, challengeType
id title isRequired challengeType
ae9defd7acaf69703ab432ea Smallest Common Multiple true 5

Description

Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters. The range will be an array of two numbers that will not necessarily be in numerical order. For example, if given 1 and 3, find the smallest common multiple of both 1 and 3 that is also evenly divisible by all numbers between 1 and 3. The answer here would be 6. Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.

Instructions

Tests

tests:
  - text: <code>smallestCommons([1, 5])</code> should return a number.
    testString: assert.deepEqual(typeof smallestCommons([1, 5]), 'number', '<code>smallestCommons([1, 5])</code> should return a number.');
  - text: <code>smallestCommons([1, 5])</code> should return 60.
    testString: assert.deepEqual(smallestCommons([1, 5]), 60);
  - text: <code>smallestCommons([5, 1])</code> should return 60.
    testString: assert.deepEqual(smallestCommons([5, 1]), 60);
  - text: <code>smallestCommons([2, 10])</code> should return 2520.
    testString: assert.deepEqual(smallestCommons([2, 10]), 2520);
  - text: <code>smallestCommons([1, 13])</code> should return 360360.
    testString: assert.deepEqual(smallestCommons([1, 13]), 360360);
  - text: <code>smallestCommons([23, 18])</code> should return 6056820.
    testString: assert.deepEqual(smallestCommons([23, 18]), 6056820);

Challenge Seed

function smallestCommons(arr) {
  return arr;
}


smallestCommons([1,5]);

Solution

function gcd(a, b) {
    while (b !== 0) {
        a = [b, b = a % b][0];
    }
    return a;
}

function lcm(a, b) {
    return (a * b) / gcd(a, b);
}

function smallestCommons(arr) {
  arr.sort(function(a,b) {return a-b;});
  var rng = [];
  for (var i = arr[0]; i <= arr[1]; i++) {
    rng.push(i);
  }
  return rng.reduce(lcm);
}