Skip to content

Instantly share code, notes, and snippets.

@StartAutomating
Created August 15, 2025 18:47
Show Gist options
  • Save StartAutomating/8d2bbedbfd371ff70e076d8260a08d4b to your computer and use it in GitHub Desktop.
Save StartAutomating/8d2bbedbfd371ff70e076d8260a08d4b to your computer and use it in GitHub Desktop.
Gist get me primes
# Calculate primes reasonably quickly with the Sieve of Eratosthenes
# Pipe in any positive whole number to see if it is prime.
filter prime {
$in = $_
if ($in -isnot [int]) { return }
if ($in -eq 1) { return $in }
if ($in -lt 1) { return}
if (-not $script:PrimeSieve) {
$script:PrimeSieve = [Collections.Queue]::new()
$script:PrimeSieve.Enqueue(2)
}
if ($script:PrimeSieve -contains $in) { return $in}
foreach ($n in $script:PrimeSieve) {
if (($n * 2) -ge $in) { break }
if (-not ($in % $n)) { return }
}
$script:PrimeSieve.Enqueue($in)
$in
}
Measure-Command { $primes = 1..1kb | prime }
$primes.Count
# $primes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment