Skip to content

Instantly share code, notes, and snippets.

@jeanmw
Last active August 2, 2017 22:39
Show Gist options
  • Save jeanmw/a5b1c4f1d17cbd5cea7f2950b95d6eb4 to your computer and use it in GitHub Desktop.
Save jeanmw/a5b1c4f1d17cbd5cea7f2950b95d6eb4 to your computer and use it in GitHub Desktop.
Iterative and recursive methods to find if a number is a prime in JavaScript
function isPrime(num) {
var count = 2;
while(count < num) {
if(num % count == 0) {
return false;
}
count ++;
}
return true;
}
function isPrimeRecursive(num, half) {
if(half === 0 || num === 1) {
return true;
}
half = half || parseInt(num/2);
if(num % half === 2 && half !== 1) {
return false;
} else {
return isPrime(num, half - 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment