Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 25 additions & 20 deletions algorithms/math/checkPrime.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
// JavaScript implementation of prime number checking
//
// Author: Nikolas Huebecker

function isPrime(n){
var divisor = 2;

while (n > divisor){
if(n % divisor == 0){
return false;
}else {
divisor++;
}
}
"use strict";

/**
* JS implementation of primality testing
* @param {number} n
* @author Nikolas Huebecker
* @author Ricardo Fernández Serrata
*/
const isPrime = n => {
if (!Number.isInteger(n))
return false;

n = Math.abs(n);

if (n % 2 === 0)
return n === 2;

const rt = Math.sqrt(n);

for (let d = 3; d <= rt; d += 2)
if (n % d === 0)
return false;

return true;
}

// Test

console.log("The number 137 is prime:"
console.log(isPrime(137))


console.log("The number 16 is prime:"
console.log(isPrime(16))
for (const n of [137, 16, 24, 127, 11])
console.log(`The number ${n} is prime: ${isPrime(n)}`)