Detect prime numbers (v4)

Revision 4 of this benchmark created by Felix Böhm on


Preparation HTML

<script>
  var arr = [7, 10, 37, 60, 373, 390, 1427, 7879, 7881];
  
  // Code taken from http://ejohn.org/apps/learn/ by John Resig
  
  function isPrime(num) {
   var prime = num != 1; // Everything but 1 can be prime
   for (var i = 2; i < num; i++) {
    if (num % i == 0) {
     prime = false;
     break;
    };
   };
   return prime;
  };
  
  function isPrimeCached(num) {
   if (isPrimeCached.cache[num] !== null) {
    return isPrimeCached.cache[num];
   };
   var prime = num != 1; // Everything but 1 can be prime
   for (var i = 2; i < num; i++) {
    if (num % i == 0) {
     prime = false;
     break;
    };
   };
   isPrimeCached.cache[num] = prime;
   return prime;
  };
  isPrimeCached.cache = {};
  
  // By Devon Govett
  
  function isPrimeFaster(num) {
   var prime = num != 1 || num != 2;
   for (var i = 3; i < num; i += 2) { //ignore even numbers > 2
    if (num % i == 0) {
     prime = false;
     break;
    }
   }
   return prime;
  }
  
  function isPrimeFasterCached(num) {
   if (isPrimeFasterCached.cache[num] !== null) {
    return isPrimeFasterCached.cache[num];
   };
  
   var prime = num != 1 || num != 2;
   for (var i = 3; i < num; i += 2) { // ignore even numbers > 2
    if (num % i == 0) {
     prime = false;
     break;
    }
   }
  
   isPrimeFasterCached.cache[num] = prime;
   return prime;
  };
  isPrimeFasterCached.cache = {};
  
  
  // Code by Devon Govett — http://twitter.com/devongovett/status/20019256843, inspired by http://mths.be/ahf
  
  function isPrimeRegex(n) {
   return Array(n + 1).join('1').search(/^1?$|^(11+?)\1+$/) === -1;
  };
  
  function fermat(p) {
   return (Math.pow(4, p) % p) === (4 % p);
  }
  
  function fermat_simplified(p) {
   return (Math.pow(4, p - 1) % p) === 1;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Fermat's little theorem
// a^(p) mod p = a mod p
var i = arr.length;
while (i--) {
 fermat(arr[i]);
};
ready
isPrimeFasterCached()
var i = arr.length;
while (i--) {
 isPrimeFasterCached(arr[i]);
};
ready
isPrimeFaster()
var i = arr.length;
while (i--) {
 isPrimeFaster(arr[i]);
};
ready
isPrimeRegex()
var i = arr.length;
while (i--) {
 isPrimeRegex(arr[i]);
};
ready
isPrimeCached()
var i = arr.length;
while (i--) {
 isPrimeCached(arr[i]);
};
ready
isPrime()
var i = arr.length;
while (i--) {
 isPrime(arr[i]);
};
ready
Fermat's little theorem simplified
// a^(p-1) mod p = 1
var i = arr.length;
while (i--) {
 fermat_simplified(arr[i]);
};
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Devon Govett on
  • Revision 2: published by Devon Govett on
  • Revision 4: published by Felix Böhm on
  • Revision 7: published by Maxim Zorin on
  • Revision 10: published on
  • Revision 11: published by Sanel Deljkic on