JavaScript(JS) JS print all prime numbers in an interval
To print all prime numbers in a given interval using JavaScript, you can use the following code:
function printPrimes(start, end) { for (let i = start; i <= end; i++) { let isPrime = true; for (let j = 2; j <= Math.sqrt(i); j++) { if (i % j === 0) { isPrime = false; break; } } if (isPrime && i > 1) { console.log(i); } } } // Example usage: printPrimes(1, 100);
In this code, we define a function called printPrimes
that takes in two parameters, start
and end
, representing the interval to search for prime numbers.
We then loop through each number in the interval using a for
loop. For each number, we check if it is prime by looping through all numbers from 2 to the square root of the number. If the number is divisible by any of these numbers, then it is not prime and we set the isPrime
variable to false
. We then use an if
statement to check if isPrime
is still true
after the inner loop and if the number is greater than 1 (since 1 is not considered prime). If so, we print the number to the console using console.log()
.