Improve prime algorithm

main
Trivernis 3 months ago
parent 37337b3ea7
commit 6f153b95d5

@ -33,9 +33,10 @@ primesIn = \max ->
acc |> List.append head |> filterPrimesRec tail
[_, .. as tail] -> filterPrimesRec acc tail
# Only take odd numbers so we only have to check half of all numbers
[2]
|> List.concat (List.range { start: At 3u64, end: At max, step: 2 })
|> \l -> filterPrimesRec [] l
|> \l -> filterPrimesRec (List.withCapacity (Num.toNat (Num.divTrunc max 4))) l
isPrimePost = \list, n ->
isPrimeRec = \l, limit ->
@ -44,6 +45,7 @@ isPrimePost = \list, n ->
[head, .. as tail] ->
if Num.isMultipleOf n head then
Bool.false
# Limit check if we exceeded the squareroot
else if head > limit then
Bool.true
else
@ -53,11 +55,14 @@ isPrimePost = \list, n ->
sqrtF = Num.sqrt (Num.toF32 n)
sqrtI = Num.floor sqrtF
# Check for an integer square root without ceiling operations to avoid linker errors
if Num.isZero (sqrtF - Num.toF32 sqrtI) then
Bool.false
else
isPrimeRec list (sqrtI + 1)
### TESTING STUFF ###
# Dumb primes for testing
countPrimesIn : U64 -> Nat
countPrimesIn = \limit ->
List.range { start: At 2, end: At limit }
@ -87,3 +92,20 @@ expect
actual
)
expect
(
countPrimesIn 2
|> \expected ->
dbg expected
expected
)
== (
List.len (primesIn 2)
|> \actual ->
dbg actual
actual
)

Loading…
Cancel
Save