diff --git a/algorithms/math/checkPrime.js b/algorithms/math/checkPrime.js index bf2f4b8..66f0a60 100644 --- a/algorithms/math/checkPrime.js +++ b/algorithms/math/checkPrime.js @@ -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)}`)