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 1 commit
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: 24 additions & 1 deletion 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 @@ -221,7 +225,11 @@ export async function findPrime (original, sophie = false) {
const tests = generateTests(tested, keyFrame, simultaneous)

// Turn the tests into `openssl prime` processes, and wait for them to complete.
const result = await Promise.all(tests.map(i => execPromise(`openssl prime ${i}`)))
const result = await Promise.all(
tests
.filter(i => isPossiblyPrime(i))
TotalTechGeek marked this conversation as resolved.
Show resolved Hide resolved
.map(i => execPromise(`openssl prime ${i}`))
)

// Filter out any of the results that are not prime.
const successes = result.filter(i => !i.stdout.includes('not prime'))
Expand Down Expand Up @@ -255,3 +263,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
}