This is the 21st day of my participation in Gwen Challenge

Today, WHEN I was practicing FreeCodeCamp, I found a very interesting primary algorithm problem, so I want to share it with you.

Topic describes

Find the least common multiple of the supplied parameter that can be equalized by both and all serial numbers in the range between these parameters.

The range will be an array of two numbers, not necessarily in numeric order.

For example, given 1 and 3, find the least common multiple of 1 and 3, which is also divisible by all the numbers between 1 and 3. Here the answer is 6.

Test case

Their thinking

When I first saw this problem, I was thinking, well, what’s the least common multiple? But it’s not that easy, because they’re not asking us to find the least common multiple of two numbers, they’re asking us to find the least common multiple of this range, so it’s very important to understand the problem.

Difficulty: How to find the least common multiple of two numbers

Train of thought

  1. First, the larger of the two numbers defaults to the least common multiple.
  2. Through the while loop, as long as the default least common multiple is less than or equal to the product of two numbers, if the default least common multiple tends to zero for the number on the left, it is the least common multiple. Otherwise, let the default least common multiple plus the value on the right continue the loop.

code

// Get the least common multiple of the function
    function getSCM(left, right) {

        // The least common multiple is right by default
        let SCM = right;

        while (SCM <= right * left) {
            if (SCM % left === 0) {
                return SCM
            } else{ SCM = SCM + right; }}}Copy the code

The problem solving code

function smallestCommons(arr) {
    arr.sort((next, pre) = > next - pre);

    // Get the least common multiple of the function
    function getSCM(left, right) {

        // The least common multiple is right by default
        let SCM = right;

        while (SCM <= right * left) {
            if (SCM % left === 0) {
                return SCM
            } else{ SCM = SCM + right; }}}// Generate an array
    const newArr = [];
    for (let i = arr[0]; i <= arr[1]; i++) {
        newArr.push(i);
    }
    let result = arr[0] * (arr[0] + 1);
    // Update the least common multiple through a loop
    for (let i = 2; i < newArr.length; i++) {
        result = getSCM(newArr[i], result);
    }
    return result;
}


smallestCommons([1.5]);
Copy the code

What does this subject tell us

  1. Learn how to find the least common multiple of two numbers in a loop.
  2. Learn how to get the least common multiple of a range by updating it.

Refer to the link

  • Find the least common multiple of a range of numbers