MestreALMO
MestreALMO

Reputation: 171

How to check if a number is prime? and if is not, how to increment the number until the function returns the next prime number?

Thing is I do believe I already built the code that make it happen, the problem is that I'm trying to use it as an answer for the challenge at jschallenger.com, but the page do not accept my code as a valid answer.

Can anyone explain to me why the site does not accepts my code and how I can fix it? My code is right, right?

Here is my code:

function checkPrime(number) {
  for (var i = 2; i < number; i++) {
    if (number % i === 0) {
      return false;
    }
  }
  return true;
}

function myFunction(number) {
  if (checkPrime(number)) {
    return number;
  } else {
    while (checkPrime(number) === false) {
      number++;
    }
  }
  return number;
}

console.log(myFunction(38)); //the return should be 41
console.log(myFunction(7)); //the return should be 7
console.log(myFunction(115)); //the return should be 127
console.log(myFunction(2000)); //the return should be 2003

Upvotes: 0

Views: 2910

Answers (2)

Mojtaba Seyedi
Mojtaba Seyedi

Reputation: 1

function myFunction(a) {
  for (let i = 2; i < a; i++) {
    if (a % i === 0) {
      return myFunction(++a);
    }
  }

  return a;
}

Upvotes: 0

Robson
Robson

Reputation: 2032

Looks like the site only allows you to have the function and nothing else. Specifically in this situation: no separate functions. So if I put your checkPrime function inside myFunction it will pass successfully.

function myFunction(number) {
  function checkPrime(number) {
    for (var i = 2; i < number; i++) {
      if (number % i === 0) {
        return false;
      }
    }
    return true;
  }
  if (checkPrime(number)) {
    return number;
  } else {
    while (checkPrime(number) === false) {
      number++;
    }
  }
  return number;
}

Upvotes: 1

Related Questions