Print Prime Numbers from 1 to N using Basic Approach
Here’s a simple implementation to find and print prime numbers from 1 to N. The below code consists of two functions: isPrime and printPrimeNumbers.
- isPrime(num) function: This function checks if a given number num is a prime number or not. It iterates from 2 to the square root of num (inclusive) and checks if num is divisible by any of these numbers. If it is, the function returns false, indicating that num is not a prime number. If num is not divisible by any number in the range, the function returns true, but only if num is greater than 1 (since 1 is not considered a prime number). This is an efficient way to check for primality, as it reduces the number of iterations needed.
- printPrimeNumbers(n) function: This function prints all prime numbers up to a given number n. It iterates from 2 to n and uses the isPrime function to check if each number is prime. If a number is prime, it is printed to the console.
Javascript
function isPrime(num) { for (let i = 2; i <= Math.sqrt(num); i++) { if (num % i === 0) { return false ; } } return num > 1; } function printPrimeNumbers(n) { for (let i = 2; i <= n; i++) { if (isPrime(i)) { console.log(i); } } } printPrimeNumbers(100); |
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
JavaScript Program to Print Prime Numbers from 1 to N
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In this article, we’ll explore how to create a JavaScript program to print all prime numbers from 1 to a given number N.
To find prime numbers from 1 to N, we need to:
- Iterate through all numbers from 2 to N (since 1 is not a prime number).
- For each number, check if it is divisible by any number other than 1 and itself.
- If a number is only divisible by 1 and itself, it is a prime number.
Contact Us