How to Find Prime Numbers in JavaScript?

Estimated read time 2 min read

You can find prime numbers in JavaScript by using a loop to iterate over the numbers, and checking if they are divisible by any number less than themselves. If a number is not divisible by any other number, it is considered to be a prime number.

Here’s an example implementation:

function isPrime(num) {
  if (num <= 1) {
    return false;
  }

  for (let i = 2; i < num; i++) {
    if (num % i === 0) {
      return false;
    }
  }

  return true;
}

const primeNumbers = [];
for (let i = 2; i <= 100; i++) {
  if (isPrime(i)) {
    primeNumbers.push(i);
  }
}

console.log(primeNumbers);
// 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]

This code defines the isPrime() function, which takes a number as an argument and returns true if the number is a prime number, and false otherwise. The isPrime() function uses a loop to iterate over the numbers from 2 to num-1, and checks if num is divisible by any of them. If num is divisible by any of them, it returns false. If the loop completes without finding any divisors, num is considered to be a prime number and the function returns true.

The code then uses another loop to iterate over the numbers from 2 to 100, and calls the isPrime() function for each number. If the isPrime() function returns true, the number is added to the primeNumbers array.

Note that this is just one implementation, and there are many other ways to find prime numbers, including more efficient algorithms.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply