27
Mar
09

[JavaScript] Determine if Number is Prime

Little script to determine if a number is prime or not.
Can be sped up by removing the document.write lines, which are only displayed to the user to show what tests are being run.

function isPrime(pTest) {
   if((pTest == 2) || (pTest==-2)) {
      document.write('Number [' + pTest + '] is prime' + "<br > n");
      return true;
   } else if(pTest%2 == 0) {
      document.write(pTest + "/" + 2 + " Remainder = " + pTest%2 + "<br > ");
      return false;
   } else if ((pTest==1) || (pTest==0) || (String(pTest).indexOf('.') != -1)) {
      document.write('Numbers [0; 1; decimals] are not prime' + "<br > n");
      return false;
   } else {
      for (i = 3; i * i <= pTest; i += 2) {
         if (pTest % i == 0) {
            document.write(pTest + ";/" + i + " Remainder = 0<br > ");
            return false;
         }else{
            document.write(pTest + "/" + i + " Remainder = " + pTest%i + "<br > ");
         }
      }
      return true;
   }
}

Usage:

var n = prompt("Enter a number to test for prime", 53);
alert(isPrime(n));

Would output:

53/3 Remainder = 2
53/5 Remainder = 3
53/7 Remainder = 4

[Alert]True

Advertisements

0 Responses to “[JavaScript] Determine if Number is Prime”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: