최소공배수
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]));
Reference
이 문제에 관하여(최소공배수), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/rthefounding/smallest-common-multiple-k2h텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)