My code is off. Need advice

// DO NOT CHANGE THE LINE BELOW.
const n = prompt("Enter a number: ");

/**

  • TODO: Find the largest positive prime number <= n.
  • A prime number is a natural number greater than 1 whose only
  • factors are 1 and the number itself. That is, it can only be
  • divided equally by 1 and itself.
  • Natural numbers are positive integers such as 1, 5, 201, 229999
  • etc. The number 0, fractions, decimals, and negative numbers
  • are not natural numbers.
    */
    let num = β€œβ€;

if (n < 2) {
return false
}
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
return false
}
return true
}

// DO NOT CHANGE THE LINE BELOW.
console.log(num);

But the console.log(num). I can’t change that.

It looks like you are supposed to make a function.
Which you already have the code for (but with a } in the wrong spot).
Revised:

function isPrime(n) {
  if (n < 2) {
    return false;
  }
  for (let i = 2; i <= Math.sqrt(n); i++) {
    if (n % i === 0) {
      return false;
    }
  }
  return true; // is outside the for loop
} 

And then you could do a loop (where the function is called inside of it) to find the largest prime ≀ n.

1 Like