checkPrime function returns incorrect values

ksenialke

numbers = [];
for (x = 1; x <= 1e4; x++) {
  numbers.push(x)
}
//console.log(numbers)

function checkPrime(num) {
  if (num == 1 || num == 0) {
    return 'It is a separate case'
  }
  if (num == 2) {
    return num + ' is prime'
  }
  for (var i = 2; i < num; i++) {
    if (num in numbers) {
      if (num % i === 0) return num + ' is not prime';
      else {
        return num + ' is prime';
      }
      return num !== 1;
    } else {
      return num + ' is not in range';
    }
  }

}
console.log(checkPrime(27));

Hi. In the above code, I tried to create a function which returns information about whether a number is prime or not.

However, it fails in some cases. Like eg. in the case of 27 or 145, it returns the values are prime, which obviously is false. How can I amend this program to make it work?

Also, what is the smartest way of merging the case for number 2 and the rest prime numbers?

Thanks in advance and sorry if this is too basic, I could not find the right answer anywhere else.

Jorge

I have rewritten the code to provide the right answer

numbers = [];
for (x = 1; x <= 1e4; x++) {
  numbers.push(x)
}
//console.log(numbers)

function checkPrime(num) {
  if (num == 1 || num == 0) {
    return 'It is a separate case'
  }
  // check this condition outside the loop
  if (!(num in numbers)) {
    return num + ' is not in range';
  }
  if (num == 2) {
    return num + ' is prime'
  }
  for (var i = 2; i < num; i++) {
    if (num % i === 0) {
      return num + ' is not prime';
    }
  }
  return num + ' is prime';

}

console.log(checkPrime(27));

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related