StudyMaths.co.uk

GCSE maths revision

Username:
Password:
Register?

Using JavaScript to check if a number is prime

This function works taking an input number and trying to divide it by all the numbers from 2 to the square root of the input number. If any of these numbers divides the original number exactly then that number cannot be prime.

The function also checks to see if the input number is less than 2 or not an integer and if so returns false.

function isPrime(n) {

   // If n is less than 2 or not an integer then by definition cannot be prime.
   if (n < 2) {return false}
   if (n != Math.round(n)) {return false}

   // Now assume that n is prime, we will try to prove that it is not.
   var isPrime = true;

   // Now check every whole number from 2 to the square root of n. If any of these divides n exactly, n cannot be prime.
   for (var i = 2; i <= Math.sqrt(n); i++) {
      if (n % i == 0) {isPrime = false}
   }

   // Finally return whether n is prime or not.
   return isPrime;

}

Note we only have to check up to the square root of the input number as any factors greater than this will have a corresponding smaller factor pair.

Use the code to check if a number is prime!

See the code in action below. Choose a number and test whether it is prime.

Enter a number in the box above.