Thursday, July 23, 2020

Smallest common multiple

From: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple

Materials used:
https://en.wikipedia.org/wiki/Euclidean_algorithm
https://en.wikipedia.org/wiki/Least_common_multiple

Intermediate Algorithm Scripting: Smallest Common Multiple

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.

smallestCommons([1, 5]) should return a number.

smallestCommons([1, 5]) should return 60.

smallestCommons([5, 1]) should return 60.

smallestCommons([2, 10]) should return 2520.

smallestCommons([1, 13]) should return 360360.

smallestCommons([23, 18]) should return 6056820.


// if this causes stack overflow, search stackoverflow for better implementation.
// this would work too even if hi and lo are swapped.
const recGcd = (hi, lo) => lo === 0 ? hi : recGcd(lo, hi % lo);

// If your small code has if, has loop, or return keyword,
// don't use arrow function, just use plain old function instead.
// In fact, the arrow function will become longer due to const keyword use.
// And you need to use const, as no one modifies the behavior of arrow functions.

// function gcd(a, b) {
// let gcd = (a, b) => {
// const gcd = (a, b) => {

// this won't cause stack overflow
// this would work too even if hi and lo are swapped.
function gcd(hi, lo) {
    while (hi % lo !== 0) {
        [hi, lo] = [lo, hi % lo];
    } 
    return lo;
}

const lcm = (a, b) => a * b / gcd(a, b);

function smallestCommons(arr) {
    const lo = Math.min(...arr);
    const hi = Math.max(...arr);

    let lastLcm = lo;
    for (let i = lastLcm; i < hi; ++i) {
      lastLcm = lcm(lastLcm, i + 1);
    }
    return lastLcm;
}

console.log(gcd(252, 105));
console.log();
[
    [1, 5],
    [5, 1],
    [2, 10],
    [1, 13],
    [23, 18]
].forEach(arr => console.log(smallestCommons(arr)));

Output:
21

60
60
2520
360360
6056820

No comments:

Post a Comment