최소공배수

  • 이제 우리가 알아내려고 하는 다음 문제는 제공된 매개변수의 가장 작은 공배수를 찾는 것입니다. 이 매개변수는 이 매개변수 사이의 범위에 있는 모든 순차 수뿐만 아니라 둘 다로 균등하게 나눌 수 있습니다.
  • 예를 들어, 1과 3이 주어지면 1과 3 사이의 모든 숫자로 균등하게 나눌 수 있는 1과 3의 가장 작은 공배수를 찾으십시오. 여기서 답은 6입니다.

  • function smallestCommons(arr) {
    
    
      return arr;
    }
    
    smallestCommons([1,5]);
    


  • 대답:

  • function computeSCM(num1, num2) {
      let min = Math.min(num1, num2)
      let max = Math.max(num1, num2)
    
      for (let i = max; i <= min * max; i+= max) {
        if (i % min === 0) {
          return i; // make sure to find the smallest commmon multiple.
        }
      }
    }
    // now that we have that we need to find smallest common multiple of an array of numbers or a range.
    
    
    function smallestCommons(arr) {
      let minNum = Math.min(...arr)
      let maxNum = Math.max(...arr)
      let scm = 1;
    
      for (let j = minNum; j <= maxNum; j++) {
        scm = computeSCM(scm, j)
      }
    
    
      return scm;
    }
    
    
    console.log(smallestCommons([1,5])); will display 60.
    


  • 또는:

  • function smallestCommons(arr) {
      arr.sort((a, b) => a - b); // comparing two numbers Either way will switch the positions when a is greater than b.
    
    
      //arr.sort((a, b => {
        //a > b?-1:1
    // }); The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
      let [div, num] = arr
      while (div < arr[1]) {
        if (num % div == 0) {
        div++
      } else {
      num += arr[1]; // arr[1] continues being 5 because given the array [1, 5] as an example, arr[1] will always be 5, but the value stored in num increases with each loop from 5 to 10 to 15 to 20 and so on. The first loop tests 5%1, 5%2, 5%3, 5%4 (until it gets a remainder). Second loop tests 10%1, 10%2, 10%3, 10%4. Third loop tests 15%1, 15%2, 15%3, 15%4. And so on until there is no remainder in the loop, which means we have found our solution num. The reason we are not testing divisor 5 is because our dividend is always a multiple of 5 and so we know it will have no remainder when divided by 5 (that's why we can use div < arr[1] instead of div <= arr[1]).
      div = arr[0];
      }
    }
      return num
    }
    
    
    console.log(smallestCommons([1,5]));
    

    좋은 웹페이지 즐겨찾기