What you need is a formula to check whether the current number in this loop is a prime number or not.
Let’s Create a function to check if a number is a prime number.
function isPrime(num) {
for(let i = 2; i <= Math.sqrt(num); i++){
if(num % i === 0) return false;
}
return num > 1;
}
Then in the loop, we can call the function to find all prime numbers.
for(let i = 2; i <= 100; i++){
if( isPrime(i) ) {
console.log(i + ' is a prime number.');
}
else{
// console.log(i + ' is not a prime number');
}
}
You are doing a lot of extra loops. For example, if the num is 100 or 1000 then the loop will run 1000 times. But Math.sqrt(1000) is only 31.
If you want to keep the function more simple you can try the function below
function isPrime(num) {
for (let i = 2; i * i <= num; i++)
if (num % i === 0)
return false;
return num > 1;
}