问题描述
function checkRange(num,temp) {
for (var i = 1; i < num; i++) {
console.log(temp % i,i,temp);
if (temp % i != 0) {
return false;
}
}
return true;
}
function smallestCommons(arr) {
arr.sort((a,b) => {return a > b})
var two = [arr[1]];
var check = false;
while (check == false) {
two.push(two[two.length - 1] + arr[1])
if (checkRange(arr[1],two[two.length - 1]) == true) {
check = true;
return two[two.length - 1];
}
}
console.log(two);
// not sure what to do with this
return two[two.length - 1];
}
smallestCommons([1,13]);
所以我确实意识到这可能是一个无限循环,但我想知道为什么会这样。
我的代码不适用于:
smallestCommons([1,13]) 应该返回 360360。
smallestCommons([23,18]) 应该返回 6056820。
代码的工作步骤如下:
创建一个循环,将继续添加带有 arr[1] 的最后一个索引,并验证是否可以为数组的最后一个元素平均划分计数到 arr[0] 的每个数字。
解决方法
这是我学习时的回答:
function checkall(arr,lcm) {
let num1 = arr[0]
let num2 = arr[1]
// Get the start number
let first = (num1 < num2) ? num1 : num2;
// Get the end number
let last = (num1 > num2) ? num1 : num2;
while (first != last) {
// Check if lcm is divisble
if (lcm % first != 0) {
// If not then get an lcm of the number and existing lcm
lcm = getlcm(first,lcm)
}
// Increment first
first++
}
// Return the end lcm
return lcm
}
function smallestCommons(arr) {
// Get the two numbers
let num1 = arr[0]
let num2 = arr[1]
// Feed the array and lcm into the checkall function
return checkall(arr,getlcm(num1,num2))
}
function getlcm(num1,num2) {
// Get the minimum number out of both
let min = (num1 > num2) ? num1 : num2;
while (true) {
// Check if a number is divisible by both
if (min % num1 == 0 && min % num2 == 0) {
// If matches,this is the lcm
// Break the loop and return the lcm
return min
break;
}
// Increment the number
min++;
}
}
console.log(smallestCommons([1,13]))
console.log(smallestCommons([23,18]))
console.log(smallestCommons([2,10]))
我发现它超时的原因是它效率低下并且需要太多循环。
Keshav 的回答似乎也需要很多循环,所以我不确定为什么它不会超时......