Print All Prime Numbers in a Given Range
Instructions
Write a function that prints all the prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Examples
Here are a few examples to illustrate how the printPrimes
function works:
Example 1
Input: start = 0, end = 10
Output: 2, 3, 5, 7
Example 2
Input: start = 10, end = 20
Output: 11, 13, 17, 19
Example 3
Input: start = 20, end = 30
Output: 23, 29
Solution
The example solution provided demonstrates a function called printPrimes
that prints all the prime numbers within a given range. The function uses a loop to check each number in the range and determine if it is prime by checking for divisors.
Print Prime Numbers
const printPrimes = (start, end) => {
const isPrime = (num) => {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
};
for (let i = start; i <= end; i++) {
if (isPrime(i)) {
console.log(i);
}
}
};
// Example usage:
printPrimes(0, 10); // Output: 2, 3, 5, 7