Skip to content

Commit

Permalink
[IMP] Halved execution time for Prime number checks. (#501)
Browse files Browse the repository at this point in the history
  • Loading branch information
Byloth authored Nov 19, 2022
1 parent cc7a1fe commit af7972d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
6 changes: 5 additions & 1 deletion packages/number-is-prime/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ function isPrime(number) {
return false;
}

for (var i = 2; i <= Math.sqrt(number); i++) {
if (number % 2 === 0) {
return (number === 2);
}

for (var i = 3; i <= Math.sqrt(number); i += 2) {
if (number % i === 0) {
return false;
}
Expand Down
12 changes: 6 additions & 6 deletions packages/number-is-prime/index.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
var numberIsPrime = isPrime;

/*
isPrime(1); // false
isPrime(2); // true
Expand All @@ -13,7 +11,7 @@ var numberIsPrime = isPrime;
isPrime([]); // throws
*/

function isPrime(number) {
export default function isPrime(number) {
if (!Number.isInteger(number)) {
throw new Error('just-is-prime expects an integer argument');
}
Expand All @@ -22,13 +20,15 @@ function isPrime(number) {
return false;
}

for (var i = 2; i <= Math.sqrt(number); i++) {
if (number % 2 === 0) {
return (number === 2);
}

for (let i = 3; i <= Math.sqrt(number); i += 2) {
if (number % i === 0) {
return false;
}
}

return true;
}

export {numberIsPrime as default};

0 comments on commit af7972d

Please sign in to comment.