Hello, i tested this code in the console and it returns the correct output but freecodecamp does not recognise it as right. Anybody can see why this is happening?
THanks
function smallestCommons(arr) {
//sort the original array
if(arr[0] > arr[1]) {
arr = arr.sort();
}
//creating a new array and pushing all the numbers in the range to it
let range = [];
for (let i = arr[0]; i <= arr[1]; i++) {
range.push(i);
}
//take out the 1 from range if it's there
if (range[0] === 1) {
range.shift();
}
for (let i = range[range.length -1] + 1; i < Infinity; i++) {
let mySwitch = true;
for (let j of range) {
if (i%j === 0) {
mySwitch = mySwitch && true;
} else mySwitch = mySwitch && false;
} if (mySwitch) {
console.log(i);
return i;
}
}
}
smallestCommons([1,5]);
It takes too long to run (for example, I tried to run it on http://pythontutor.com/javascript.html#mode=edit, and that bailed out with an error message saying there were more than 1000 operations), so the test times out — you need to look at ways to optimise it (this is one of the key things that challenges like this teach you). I checked it in
Ok, the first loop i wrote was really dumb because i was iterating through every number like so:
for (let i = range[range.length -1] + 1; i < Infinity; i++)
Now i’ve changed it and it looks like this:
for (let i = range[range.length -1] *2; i < Infinity; i = i + range[range.length -1])
This one though iterates through only multiples of the biggest number in the range so the operationsa should be drastically diminished. Still nothing has changed, my solution doesn’t get accepted.
This is the my full updated solution:
function smallestCommons(arr) {
//sort the original array
if(arr[0] > arr[1]) {
arr = arr.sort();
console.log(arr);
}
//creating a new array and pushing all the numbers in the range to it
let range = [];
for (let i = arr[0]; i <= arr[1]; i++) {
range.push(i);
}
//take out the 1 from range if it's there
if (range[0] === 1) {
range.shift();
}
for (let i = range[range.length -1] *2; i < Infinity; i = i + range[range.length -1]) {
let mySwitch = true;
for (let j of range) {
if (i%j === 0) {
mySwitch = mySwitch && true;
} else mySwitch = mySwitch && false;
} if (mySwitch) {
console.log(i);
return i;
}
}
}
smallestCommons([23, 18]);