Find the largest prime numbers with a given number

Question:
Given a number, find the largest prime numbers less than or equal to it.

Answer:

function isPrimeNumber(value) {
  for (var i=2; i<=Math.ceil(Math.sqrt(value)); i++)
  {
    if (value % i === 0)
    {
      return false;
    }
  }

  return true;
}

function findLargestPrimeNumberLessThan(value) {
  if (isNaN(value)) {
    throw "Not a number."
  }

  var input = Math.floor(value);
  if (input <== 1) {
    throw "number should be greater than or equal to 2";
  }

  for (var i=input; i>=2; i--) {
    if (isPrimeNumber(i))
    {
      break;
    }
  }

  return i;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s