Program For Prime Numbers in Javascript

Spread the love

This article will teach us how to find Prime Numbers in Javascript. Prime numbers are the numbers that have only two factors. They are 1 and itself. We will share two programs in javascript where one will return whether the entered number is a prime number or not and the other one will return the list of prime numbers under the input.

Prime Numbers in Javascript

Program to Find whether the Entered Value is a Prime Number or Not

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

  for (let i = 2; i <= Math.sqrt(number); i++) {
    if (number % i === 0) {
      return false;
    }
  }

  return true;
}

// Example usage:
const numToCheck = 17;
if (isPrime(numToCheck)) {
  console.log(`${numToCheck} is a prime number.`);
} else {
  console.log(`${numToCheck} is not a prime number.`);
}

In the above program, we have created a function called isPrime() that takes a number as input and returns true if the number is a prime number. We are using one of the native javascript methods Math.sqrt() to determine the square root of the input number. We are checking it in a loop that starts from 2 because 1 will be the default factor of any number.

Once the check is done, we are printing it to the console for our convenience at this point in time.

Program to Return the List of Prime Numbers up to the entered Input Value

function getPrimesUnderLimit(limit) {
  const primes = [];

  for (let i = 2; i < limit; i++) {
    if (isPrime(i)) {
      primes.push(i);
    }
  }

  return primes;
}

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

  for (let i = 2; i <= Math.sqrt(number); i++) {
    if (number % i === 0) {
      return false;
    }
  }

  return true;
}

// Example usage:
const limit = 30;
const primeList = getPrimesUnderLimit(limit);
console.log(`Prime numbers under ${limit}: ${primeList.join(', ')}`);

In the above program, we are using a function called getPrimeUnderLimit() to return the list of prime numbers under the input given. We are using the above program isPrime() to determine whether the given number is a prime number.

We are using an array primeList[] array to create the list of prime numbers that return from the getPrimeUnderLimit() function and printing it to the console by making it a string that is divided by a comma(,) for our convenience.

Leave a Comment