mrugesh 22afc2a0ca feat(learn): python certification projects (#38216)
Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
Co-authored-by: Kristofer Koishigawa <scissorsneedfoodtoo@gmail.com>
Co-authored-by: Beau Carnes <beaucarnes@gmail.com>
2020-05-27 13:19:08 +05:30

1.7 KiB

id, challengeType, isHidden, title, forumTopicId
id challengeType isHidden title forumTopicId
5900f3711000cf542c50fe84 5 false Problem 5: Smallest multiple 302160

Description

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to n?

Instructions

Tests

tests:
  - text: <code>smallestMult(5)</code> should return a number.
    testString: assert(typeof smallestMult(5) === 'number');
  - text: <code>smallestMult(5)</code> should return 60.
    testString: assert.strictEqual(smallestMult(5), 60);
  - text: <code>smallestMult(7)</code> should return 420.
    testString: assert.strictEqual(smallestMult(7), 420);
  - text: <code>smallestMult(10)</code> should return 2520.
    testString: assert.strictEqual(smallestMult(10), 2520);
  - text: <code>smallestMult(13)</code> should return 360360.
    testString: assert.strictEqual(smallestMult(13), 360360);
  - text: <code>smallestMult(20)</code> should return 232792560.
    testString: assert.strictEqual(smallestMult(20), 232792560);

Challenge Seed

function smallestMult(n) {
  // Good luck!
  return true;
}

smallestMult(20);

Solution

function smallestMult(n){
  function gcd(a, b) {
    return b === 0 ? a : gcd(b, a%b); // Euclidean algorithm
  }

  function lcm(a, b) {
    return a * b / gcd(a, b);
  }
  var result = 1;
  for(var i = 2; i <= n; i++) {
    result = lcm(result, i);
  }
  return result;
}