Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript prime number check

Tags:

javascript

I've been trying to pass a challenge for so long, and despite reading up multiple solutions and advice online I can't seem to apply it correctly.

The instructions are "Define a function isPrime that takes one integer argument and returns true or false depending on if the integer is a prime."

I've tried a lot of things but this is the furthest I've been able to get:

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

  for (var i = 2; i < num; i++) 
    if (num % i === 0) return false;
    else return true;
}

But then I'm told: "9 is not a prime number."

Any help would be appreciated and thanks!

like image 850
nonono Avatar asked Mar 11 '23 14:03

nonono


2 Answers

You should avoid the else case and return only after for loop completion. Although for loop count can be reduced by updating condition to i <= Math.sqrt(num) ( as @PatrickRoberts suggested ).

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

  // storing the calculated value would be much 
  // better than calculating in each iteration
  var sqrt = Math.sqrt(num);

  for (var i = 2; i <= sqrt; i++) 
    if (num % i === 0) return false;
  return true;
}

FYI : In your code on the first iteration of the loop num % i === 0(9 % 2) would be false and it would return the else statement(true).

like image 188
Pranav C Balan Avatar answered Mar 29 '23 05:03

Pranav C Balan


The problem is with the else return true; in your for loop.

At the first iteration, where i is 2, just after you checked that 9 % i wasn't 0, you execute the else block and return true.

You shouldn't return true before all the iterations failed to return false.

like image 23
Aaron Avatar answered Mar 29 '23 05:03

Aaron