1

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);
babycoder
  • 184
  • 1
  • 2
  • 17

2 Answers2

2

You are very close. I will build on top of your solution. You need to return false as soon as you detect that the number is not prime. This avoids us making additional redundant calculations.

You also did not take into account the first hint.

Hint - Note: 0 and 1 are NOT considered prime numbers

For this you can simply return false if number is 0 or 1.

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

Also in your code you are using a variable isPrime to keep track of boolean values while initialising it with an empty string. This is not correct. Javascript allows this because it's weakly typed, but this is misleading. So in future if you define a variable for boolean value don't initialise it with a string ;)


To address your comment further. If you do want to stick with having a flag in your code, then you can initialise isPrime with true instead of an empty string.

That way you can get rid of the else part in the for loop, making the code shorter. I used code provided by @Commercial Suicide (by the way he did say that there are more elegant solutions) as an example:

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

const numbers = [1, 7, 11, 15, 20];
const booleans = [false, true, true, false, false];

numbers.forEach((item, i) => {
  if (isPrime(item) === booleans[i]) {
    console.log("CORRECT");
  } else {
    console.log("WRONG");
  }
})

You can then go a step further and remove the flag variable.

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

But now it should become even more clear that those flags are actually redundant, as I pointed out initially. Simply return false as soon as you detect that the number is not prime to avoid further unnecessary loop runs. From my experience in javascript over the years I can see that we are heading towards functional programming mindset. It helps to avoid variable mutations generally.

Antoni4
  • 2,535
  • 24
  • 37
  • So I can just leave that variable for the boolean blank? Like so: var isPrime; ? – babycoder Nov 25 '17 at 23:27
  • Can I leave other variables blank too that I don't want to assign a value to?Also, why don't the IF statements have the curly braces({})? Shouldn't their absence cause an error? – babycoder Nov 25 '17 at 23:45
  • If you leave a variable blank it will be "undefined". In the case of boolean value it will be the same as false, because "undefined" is falsy. You can find list of falsy values here: https://developer.mozilla.org/en-US/docs/Glossary/Falsy – Antoni4 Nov 26 '17 at 00:03
  • That is called an inline if statement. Code inside of it can be executed without curly braces. There are some examples here: https://stackoverflow.com/questions/7117873/do-if-statements-in-javascript-require-curly-braces – Antoni4 Nov 26 '17 at 00:11
2

It's because your isPrime variable can be overriding many times, simple flag (for example) will prevent this issue. I have also added check for 0, 1 and 2. There are more elegant ways to do that, but I wanted to keep your logic, here is an example with some tests:

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

const numbers = [1, 7, 11, 15, 20];
const booleans = [false, true, true, false, false];

numbers.forEach((item, i) => {
  if (isPrime(item) === booleans[i]) {
    console.log("CORRECT");
  } else {
    console.log("WRONG");
  }
})
P.S.
  • 15,970
  • 14
  • 62
  • 86
  • Can you please explain what the flag does? I am a newbie to programming and trying to practice on my own as much as possible and I haven't come across the flag yet. Thank you – babycoder Nov 25 '17 at 23:26
  • @FaizaHusain that flag was added "because your isPrime variable can be overridden many times". All it does is prevent further writes of the variable isPrime ones you set the flag to false. The only problem is that even when you set that flag to false the loop will continue to run pretty much doing nothing. Instead of the flag you can also use break to stop the loop from doing further runs, or just use return to give back the prime value straightaway. – Antoni4 Nov 26 '17 at 11:57
  • 1
    @Antoni4, thanks for explanation. And yes, I agree, `return` will be more elegant way than flag – P.S. Nov 27 '17 at 10:53