Reputation: 29
In the code below is a prime test function (returns true if prime and false if not). I am using it to print out prime numbers between 5 and 20.
The expected output is obviously 5,7,11,13,17,19
The for loop doesn't seem to iterate and just stays at 5. The output is as if the script is stuck inside an infinite while loop.
I don't know what I'm doing wrong, maybe the if statement isn't written correctly? Still a bit new to javascript.
function is_prime(number){
if (number==2 || number==3){
return true;
}
if (number==0 || number==1 || number%2==0){
return false;
}
if ((number+1)%6!=0 && (number-1)%6!=0){
return false;
}
for(i=3; i-1<=parseInt(number)**.5; i+=2){
if (number%i==0){
return false;
}
}
return true;
}
for(i=5;i<=20;i++){
if(is_prime(i)){
console.log(i)
}
}
Upvotes: 1
Views: 180
Reputation: 1
const lowerNumber = 2;
const higherNumber = 100;
for(let i = lowerNumber; i <= higherNumber; i++){
let flag = 0;
for(let j = 2; j < i; j++){
if(i % j == 0){
flag = 1;
break;
}
}
if(i > 1 && flag == 0){
console.log(i);
}
}
Upvotes: -1
Reputation: 3087
In addition to using let
in your for
loop initializers, which is just good practice anyway, it's often well-advised to use different names for different variables, for a number of reasons:
i
in one place, then you know where to look if it you get an unexpected value in i
)As an example, if I'm nesting loops, or have multiple loops in a script, I'll often start with i
and work my way down the alphabet, j
, k
, l
, etc.
Essentially any pattern you use is fine, as long as it helps you keep track of your data!
Upvotes: 0
Reputation: 127
Because you create a global variable in your loop. Declare the variable with let and everything will work fine. P.S. use strict mode will not allow you to do some stupid mistakes again
Upvotes: 0
Reputation:
You're not declaring your variable i
, so JavaScript is creating it in the global scope. In your function you also haven't declared it so it's using the same variable, and the loops don't execute as you expect.
Declare the variables with let
so that they don't clash, as in
for (let i=5;...
See Let on MDN
Upvotes: 2
Reputation: 3
Just add (let i = 5
in the for loop you need to declare that i
for(let i=5;i<=20;i++){
if(is_prime(i)){
console.log(i)
}
Upvotes: 0
Reputation: 14175
You've created a global variable named i
in your for()
loop - then you change that same variable in the function.
Use let i
in both cases.
Upvotes: 3