Design & Download
Your JS Library
in Seconds!!!

Snippet: Prime Numbers vs. Composite Numbers

Written by Christopher West (cwest) on December 09, 2015.
Determine whether a number is a prime integer or a composite integer or neither.
function isPrime(num) {
  if(!isSafeInt(num)) {
    throw new TypeError("expected a finite integer");
  }
  if(num < 2) {
    return false;
  }
  if(num < 4) {
    return true;
  }
  if(num % 2 == 0 || num % 3 == 0) {
    return false;
  }
  for(var max = parseInt(Math.sqrt(num)) + 2, check = 6; check <= max; check += 6) {
    if(num % (check - 1) == 0 || num % (check + 1) == 0) {
      return false;
    }
  }
  return true;
}

function isComposite(num) {
  return num > 1 && !isPrime(num);
}

isPrime(...) API Documentation

Description

Determines whether or not a number is a prime integer, meaning that it is an integer greater than 2 which is not evenly divisible by any number other than 1 and itself.

Parameters

  1. num {number}:
    The number to test for integer primality.

Returns

Returns true if num is a positive integer which is not evenly divisible by any other numbers other than 1 and itself. In all other cases false is returned. NOTE: 1 is neither considered prime nor composite.

isComposite(...) API Documentation

Description

Determines whether or not a number is a positive integer which is not prime.

Parameters

  1. num {number}:
    The number to test to see if it is a composite integer.

Returns

Returns true if num is a positive integer which is evenly divisible by a number besides 1 and itself. In all other cases false is returned. NOTE: 1 is neither considered prime nor composite.