Last active
December 11, 2015 00:09
-
-
Save tomaslibal/4514351 to your computer and use it in GitHub Desktop.
Trial division method to find whether a number is prime or composite.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Primality Test | |
* Checks if a given number is prime | |
* As inspired by http://www.khanacademy.org/cs/level-1-primality-test/1018672065 | |
*/ | |
function leastfactor(n) { | |
var m, i; | |
if (n == 0) return 0; | |
if (n % 1 || n*n < 2) return 1; | |
if (n %2 == 0) return 2; | |
if (n %3 == 0) return 3; | |
if (n %5 == 0) return 5; | |
m = Math.sqrt(n); | |
/* | |
factors of 2, 3, and 5 have been eliminated, so LCM(2,3,5)=30 | |
*/ | |
for (i = 7; i <= m; i += 30) { | |
if (n % i == 0) return i; | |
if (n % (i+4) == 0) return i+4; | |
if (n % (i+6) == 0) return i+6; | |
if (n % (i+10) == 0) return i+10; | |
if (n % (i+12) == 0) return i+12; | |
if (n % (i+16) == 0) return i+16; | |
if (n % (i+22) == 0) return i+22; | |
if (n % (i+24) == 0) return i+24; | |
} | |
return n; | |
} | |
/* | |
invariant: x is a number >= 2 | |
*/ | |
var isprime = function(x) { | |
if (x == leastfactor(x)) { | |
return true; | |
} else { | |
return false; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment