Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: check for divisibility by small primes #2

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
}