vendredi 24 novembre 2017

Getting Boolean values if a number is a prime number in JavaScript

I am trying to solve this problem where I need to print true or false on the console depending on the number (true if a number is Prime and false if it is not). I seem to have the solution but I know there is a mistake somewhere because I get different answers if I change the boolean values of the 2 isPrime variables.

Here is the question: Return true if num is prime, otherwise return false.

Hint: a prime number is only evenly divisible by itself and 1 Hint 2: you can solve this using a for loop.

Note: 0 and 1 are NOT considered prime numbers

Input Example:

1 7 11 15 20

Output Example:

false true true false false

My code:

function isPrime(num){
  let isPrime = '';
  for(let i = 2; i <= Math.sqrt(num); i++){
    if(num % i === 0){
      isPrime = false;
    } else {
      isPrime = true;
    }
  }
  return isPrime;

}

isPrime(11);

Aucun commentaire:

Enregistrer un commentaire