Add primality tests.

This commit is contained in:
Oleksii Trekhleb
2018-04-16 22:19:06 +03:00
parent 5699738b9b
commit 54f6aadec4
4 changed files with 1 additions and 1 deletions

View File

@ -0,0 +1,14 @@
# Primality Test
A primality test is an algorithm for determining whether an input
number is prime. Among other fields of mathematics, it is used
for cryptography. Unlike integer factorization, primality tests
do not generally give prime factors, only stating whether the
input number is prime or not. Factorization is thought to be
a computationally difficult problem, whereas primality testing
is comparatively easy (its running time is polynomial in the
size of the input).
## References
[Wikipedia](https://en.wikipedia.org/wiki/Primality_test)

View File

@ -0,0 +1,32 @@
import trialDivision from '../trialDivision';
/**
* @param {function(n: number)} testFunction
*/
function primalityTest(testFunction) {
expect(testFunction(1)).toBeTruthy();
expect(testFunction(2)).toBeTruthy();
expect(testFunction(3)).toBeTruthy();
expect(testFunction(5)).toBeTruthy();
expect(testFunction(11)).toBeTruthy();
expect(testFunction(191)).toBeTruthy();
expect(testFunction(191)).toBeTruthy();
expect(testFunction(199)).toBeTruthy();
expect(testFunction(-1)).toBeFalsy();
expect(testFunction(0)).toBeFalsy();
expect(testFunction(4)).toBeFalsy();
expect(testFunction(6)).toBeFalsy();
expect(testFunction(12)).toBeFalsy();
expect(testFunction(14)).toBeFalsy();
expect(testFunction(25)).toBeFalsy();
expect(testFunction(192)).toBeFalsy();
expect(testFunction(200)).toBeFalsy();
expect(testFunction(400)).toBeFalsy();
}
describe('trialDivision', () => {
it('should detect prime numbers', () => {
primalityTest(trialDivision);
});
});

View File

@ -0,0 +1,28 @@
/**
* @param {number} number
* @return {boolean}
*/
export default function trialDivision(number) {
if (number <= 0) {
// If number is less then one then it isn't prime by definition.
return false;
} else if (number <= 3) {
// All numbers from 1 to 3 are prime.
return true;
}
// If the number is not divided by 2 then we may eliminate all further even dividers.
if (number % 2 === 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) {
return false;
}
}
return true;
}