prime-number
is a recursive function to check if a number is prime (and a benchmark to test slow it is :)
Table of Contents
- Usage:
isPrime
, how to benchmark, primes list. - Installation: with npm or copy and paste.
- Source: embedded in this file.
- License: MIT.
Is it 1 a prime ? Some years ago I composed a djembe rhythm based on prime numbers, and it sounds better if 1 is considered prime. Casually, the algorithm implemented here defines 1 as a not prime.
Usage
As you might expect, you can do
const isPrime = console // true
There is a list of few primes available, if you want to use it
const primeNumberList = console
You can benchmark other primality check algorithms.
const isPrime = const benchmark = const from = 1000const to = NumberMAX_SAFE_INTEGER from to
Using a oneliner, let's check few primality check packages found on npm.
# node -e "require('prime-number/benchmark')(require('prime-number'))(10000, 100000)" Found 8363 primesPrimality benchmark: 44.703s # node -e "require('prime-number/benchmark')(require('is-prime'))(10000, 100000)" Found 8363 primesPrimality benchmark: 14.885ms # node -e "require('prime-number/benchmark')(require('check-prime'))(10000, 100000)" Found 654987 primesprimality benchmark: 61.613ms
So I can state that
My algorithm sucks! 🐸
Installation
With npm do
npm install prime-number
Or copy and paste the code below.
Source
First of all, do not check if num is an integer or positive or less than Number.MAX_SAFE_INTEGER
.
You can do it with some other function before calling primeNumber
.
// Remember if a number is prime.const memoize = isPrime: {} isNotPrime: {} memoizeisNotPrime1 = truememoizeisPrime2 = true /** * Check if a number is prime. * * @param * * @returns */ { // Avoid computing twice. if memoizeisPrimenum return true if memoizeisNotPrimenum return false const knowPrimes = Object for let i = 0; i < knowPrimeslength; i++ const p = NumberknowPrimesi if num === p return true if num % p === 0 memoizeisNotPrimenum = true return false for let i = 3; // Do not excede the square root of num. i * i <= num; // All prime numbers are 1 or 5 modulo 6. // Since we start with 3, this will do: 3 -> 5 -> 7 -> 11 ... +2 -> +4 -> +2 -> +4 ... i = i % 6 === 1 ? i + 4 : i + 2 if // <-- Recursion here! if num % i === 0 memoizeisNotPrimenum = true return false memoizeisPrimenum = true return true}
Export primeNumber
function
moduleexports = primeNumber