Skip to content

Instantly share code, notes, and snippets.

@ajaxsys
Created August 4, 2014 09:37
Show Gist options
  • Save ajaxsys/6cfd2c0f664e82a902ec to your computer and use it in GitHub Desktop.
Save ajaxsys/6cfd2c0f664e82a902ec to your computer and use it in GitHub Desktop.
JS check is Prime Number
function isPrime(number) {
var start = 2, end = Math.sqrt(number);
while (start <= end) {
start++;
if (number % start < 1)
return false;
}
return number > 1;
}
// Test
eq(false, isPrime(1));
eq(true, isPrime(2));
eq(true, isPrime(3));
eq(true, isPrime(5));
eq(true, isPrime(7));
eq(true, isPrime(11));
eq(true, isPrime(13));
eq(true, isPrime(17));
eq(true, isPrime(23));
eq(true, isPrime(29));
eq(true, isPrime(31));
eq(true, isPrime(37));
eq(true, isPrime(41));
function eq(exp, val) {
if (Array.isArray(exp) && Array.isArray(val)){
if (exp.toString() !== val.toString()) {
console.log('FATAL, array expected:`'+exp+'`\n but was:`'+val+'`');
}
} else if (typeof exp === 'object' && typeof val === 'object') {
if (JSON.stringify(exp) !== JSON.stringify(val)){
console.log('FATAL, object expected:`'+JSON.stringify(exp)+'`\n but was:`'+JSON.stringify(val)+'`');
}
} else {
if (exp !== val){
console.log('FATAL, expected:`'+exp+'`\n but was:`'+val+'`');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment