Skip to content

Instantly share code, notes, and snippets.

@dazfuller
Created April 17, 2022 17:48
Show Gist options
  • Save dazfuller/532d35461670b627dd54866baf2dbf8e to your computer and use it in GitHub Desktop.
Save dazfuller/532d35461670b627dd54866baf2dbf8e to your computer and use it in GitHub Desktop.
Some prime number calculations using TypeScript
/* eslint-disable max-len */
import { stdout } from 'process';
/**
* Approximates the nth prime number. This goes deliberately high so that we get a few more prime numbers
* and avoid cutting the sequence early.
* @param n The nth prime number to approximate
* @returns An approximation of the nth prime
*/
function approximateNthPrime(n: number): number {
return Math.floor(n * Math.log(n) * 1.2);
}
/**
* Get all prime numbers below a given value
* @param n The value to get prime numbers below
* @returns An array of prime numbers
*/
function getPrimesBelow(n: number): Array<number> {
const sieveLength = n + 1;
const sieve = new Array<boolean>(sieveLength);
const sieveCheckUpper = Math.ceil(Math.sqrt(n));
const primes: number[] = new Array<number>(0);
for (let i = 0; i < sieveLength; i += 1) {
sieve[i] = i % 2 !== 0;
}
primes.push(2);
for (let i = 3; i < sieveLength; i += 2) {
if (sieve[i]) {
primes.push(i);
if (i < sieveCheckUpper) {
for (let j = i * 2; j < sieveLength; j += i) {
sieve[j] = false;
}
}
}
}
return primes;
}
/**
* Gets the first n prime number values. Not the same as getting prime numbers below a value
* @param n The nth prime number
* @returns An array of prime numbers of length n
*/
function getNPrimes(n: number): Array<number> {
const upper = approximateNthPrime(n);
return getPrimesBelow(upper).slice(0, n);
}
/**
* Gets the permutations of a given input
* @param item The item to get permutations of
* @returns An array of permutations
*/
function getPermutations(item: string): Array<string> {
const permutations = new Array<string>(0);
if (item.length === 1) {
permutations.push(item);
} else {
for (let i = 0; i < item.length; i += 1) {
const c: string = item[i];
const remaining: string = item.slice(0, i) + item.slice(i + 1, item.length);
getPermutations(remaining).forEach((permutation: string) => {
permutations.push(c + permutation);
});
}
}
return permutations;
}
// Get all of the permutable primes below 1000
const primes = getPrimesBelow(1000);
const permutablePrimes = primes.filter((p) => {
const permutations: number[] = getPermutations(p.toString()).map((perm) => parseInt(perm, 10));
return permutations.every((perm) => primes.includes(perm));
});
stdout.write(`Permutable primes below 1000:\n ${permutablePrimes.join(', ')}\n`);
// Get the 1000th prime number
const thousandPrimes = getNPrimes(1000);
stdout.write(`The 1000th prime number: ${thousandPrimes.at(-1)}\n`);
@vitaly-t
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment