Improved performances of trialDivision algorithm in primality test

I improved the performances of trialDivision by performing fewer checks, while still using the same overall idea of the algorithm.
This commit is contained in:
Arthur Guiot 2021-10-05 13:19:20 -04:00 committed by GitHub
parent 4548296aff
commit e156b8afd5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -8,25 +8,19 @@ export default function trialDivision(number) {
return false;
}
if (number <= 1) {
// If number is less than one then it isn't prime by definition.
return false;
}
if (number <= 3) {
// All numbers from 2 to 3 are prime.
return true;
// If number is less than one then it isn't prime by definition. But all numbers from 2 to 3 are prime.
return number > 1;
}
// If the number is not divided by 2 then we may eliminate all further even dividers.
if (number % 2 === 0) {
// If the number is not divided by 2 or 3 then we may eliminate all further even dividers.
if (number % 2 === 0 || number % 3 === 0) {
return false;
}
// If there is no dividers up to square root of n then there is no higher dividers as well.
const dividerLimit = Math.sqrt(number);
for (let divider = 3; divider <= dividerLimit; divider += 2) {
if (number % divider === 0) {
// If there is no dividers up to square root of divider then there is no higher dividers as well. To make the algorithm more efficient, we increment by 6 everytime, and make sure to check divider + 2 as well.
for (let divider = 5; number >= (divider * divider); divider += 6) {
if (number % divider === 0 || number % (divider + 2) === 0) {
return false;
}
}