Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@geraldfullam
Last active January 17, 2018 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geraldfullam/164ce3268ebc896c0cf06e82220da409 to your computer and use it in GitHub Desktop.
Save geraldfullam/164ce3268ebc896c0cf06e82220da409 to your computer and use it in GitHub Desktop.
Extends the Math object with isPrime, optimized to check only odd numbers greater than two and less than square root.
Math.isPrime = function (n) {
if (n === 2) { return true; }
if (n % 2 === 0) { return false; }
for(let i = 3, s = Math.sqrt(n); i <= s; i += 2) {
if (n % i === 0) { return false; }
}
return n !== 1;
};
// Based on this StackOverflow answer: https://stackoverflow.com/a/40200710/2502532
// JSPerf test to demonstrate optimization: https://jsperf.com/math-isprime/1
@aaronshaf
Copy link

My ReasonML experimentation this morning at the coffee shop:

/* inspired by https://gist.github.com/geraldfullam/164ce3268ebc896c0cf06e82220da409 */

let rec checkDivisibility = (y, limit, x) => {
  if(y >= limit) {
    false
  } else if (x mod y === 0) {
    true 
  } else {
    checkDivisibility(y + 2, limit, x)
  }
};

let isPrime = (x: int): bool => {
  if (x === 2) {
    true 
  } else if(x mod 2 === 0) {
    false
  } else if (checkDivisibility(3, int_of_float(sqrt(float_of_int(x))), x)) {
    false 
  } else {
    x !== 1 
  }
};

Js.log(isPrime(1));
Js.log(isPrime(2));
Js.log(isPrime(3));
Js.log(isPrime(123));
Js.log(isPrime(1234));
Js.log(isPrime(12345));
Js.log(isPrime(12346));
Js.log(isPrime(12347));
Js.log(isPrime(123478));
Js.log(isPrime(123478));
Js.log(isPrime(1234789));
Js.log(isPrime(12347890));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment