Improve prime algorithm

main
Trivernis 10 months ago
parent 37337b3ea7
commit 6f153b95d5

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

Loading…
Cancel
Save