Created
August 15, 2025 18:47
-
-
Save StartAutomating/8d2bbedbfd371ff70e076d8260a08d4b to your computer and use it in GitHub Desktop.
Gist get me primes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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