Smallest multiple

Smallest multiple
0

#1

Iam newbie in JS, can someone explain me why my code only works till n=13?

n=14 or 15 have the same output as n=13.

smallestMult(5) should return 60. -Passed

smallestMult(7) should return 420. -Passed

smallestMult(10) should return 2520. -Passed

smallestMult(13) should return 360360. -Passed

smallestMult(20) should return 232792560. However output is: 677840

function smallestMult(n) {
let i;
let cnt = 0;
let bnd = n-1;
let mx = n;

while(cnt != bnd){
for(i = 2; i <= mx; i++){
  if(n%i == 0){
  cnt++;
  }
}
if(cnt != bnd){
cnt = 0;
n = n + mx;}
}

console.log(n);
return n;
}

smallestMult(20);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/project-euler/problem-5-smallest-multiple/


#2

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


#3

I have put the code there: https://jsconsole.com/ and it worked. Also people from stackoverflow claim it works. Environment problem maybe??


#4

I’m afraid it’s not environment :slight_smile:
Try: 677840 % 19 === 0


#5

Really?

console.log(677840 % 19 === 0); //output was false (remainder: 15)

I tried to put the whole code here: https://jsconsole.com/


#6

That’s most likely because your function hits timeout (too slow)… You goal is to write a function that will pass the test eventually.


#7

That makes sense, the code is not very effective I agree. I just wanted to solve this problem on my own, without using integrated GCD algorithm.

Anyway, thanks for explanation. Do you think it is possible to adjust the timeout somehow?


#8

Just go with gcd & lcm :slight_smile:


#9

There used to be a way to turn off the infinite loop protection (adding //noprotect at the top of your code), but I’m not sure if it still works. The timeout is there to protect you from crashing your browser if you accidentally write an infinite loop.