Skip to content

Commit

Permalink
Merge pull request #2 from ForbesLindesay/perf/faster-prime-test
Browse files Browse the repository at this point in the history
perf: check for divisibility by small primes
  • Loading branch information
TotalTechGeek committed Apr 29, 2022
2 parents 6c620bb + 0f5276e commit a1283c3
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
13 changes: 13 additions & 0 deletions generatePrimes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// @ts-check

export function generatePrimes(count) {
const primes = [2]
let nextTest = 3
while (primes.length < count) {
if (!primes.some(p => nextTest % p === 0)) {
primes.push(nextTest)
}
nextTest++
}
return primes
}
25 changes: 23 additions & 2 deletions primeSearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@ import { exec } from 'child_process'
import { cpus } from 'os';
import { createHash } from 'crypto';

import { generatePrimes } from './generatePrimes.js'

const execPromise = promisify(exec);

const SMALL_PRIMES = generatePrimes(2000).map(p => BigInt(p))

// Todo: Make this configurable.
/**
* The ways that we allow the algorithm to substitute a character.
Expand Down Expand Up @@ -107,8 +111,10 @@ function generateTest (tested, keyFrame) {
function generateTests (tested, keyFrame, count) {
let arr = []
for (let i = 0; i < count; i++) {
arr.push(generateTest(tested, keyFrame))
tested.add(hash(arr[i]))
do {
arr[i] = generateTest(tested, keyFrame)
tested.add(hash(arr[i]))
} while (!isPossiblyPrime(arr[i]))
}
return arr
}
Expand Down Expand Up @@ -255,3 +261,18 @@ export async function findPrime (original, sophie = false) {
}

}

function isPossiblyPrime(value) {
const integerValue = BigInt(value)
return isNotDivisibleBySmallPrimes(integerValue)
}

function isNotDivisibleBySmallPrimes(value) {
for (const v of SMALL_PRIMES) {
if (value % v === 0n) {
return false
}
}
return true
}

0 comments on commit a1283c3

Please sign in to comment.