2012-01-25

primes


Example



-
One of the first things I did, and one of the first things many programmers do to test their logical skills, is find a way to test for prime numbers. I've always had a thing for numbers, and primes are just weird.

In case you don't know, a prime is a whole number that cannot be divided by any whole number other than 1 or itself. To test whether a number is prime, therefore, we just need to divide it by all the whole numbers that are smaller than it. If it can be divided by one of these numbers, it is not prime.

Here's a simple script that tests if a number is prime or not.

//we take the contents of the input box, and check it with this.
function isPrime(num) {
  /* Negative numbers cannot be primes, and neither zero 
   *  nor one is prime, so we nix them here.
   */
  if (num <= 1) {
    return false;
  }
  
  /* If it is divisible by two, it is not prime, but if it IS two, 
   *  it is a prime. It's a special case, so we deal with it here.
   */
  else if ((num % 2 == 0) && (num != 2)) {
    return false;
  }
  
  /* Run through the numbers from 2 to about half the current number. 
   *  If num is found to be divisible by any of them, it is not prime,
   *  so we return false immediately. 
   */
  else {
    var halfnum = Math.round(num * 0.5);
    for (i = 2; (i <= halfnum); i++) {
      if ((num % i) == 0) {
        return false;
      }
    }
  }
  
  /*
   * If we survive the for loop, it means that nothing we have thrown 
   *  at the number can prove it is not a prime, so we assume it is one. 
   */
  return true;
}

No comments:

Post a Comment