Skip to content

Commit

Permalink
Add a test and some explanation for P39
Browse files Browse the repository at this point in the history
  • Loading branch information
Abhijit Sarkar committed Jan 5, 2024
1 parent 30b0e30 commit 9fdda15
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/Arithmetic.hs
Original file line number Diff line number Diff line change
Expand Up @@ -126,23 +126,30 @@ Given a range of integers by its lower and upper limit,
construct a list of all prime numbers in that range.
ANSWER:
Copied from: https://wiki.haskell.org/Prime_numbers,
because this prime number $hit is getting boring.
Code copied from https://wiki.haskell.org/Prime_numbers,
explanation my own.
-}
primesR :: Int -> Int -> [Int]
primesR a b = if a < 3 then 2 : xs else xs
where
xs = [i | i <- [o, o + 2 .. b], arr A.! i]
o = max (a + fromEnum (even a)) 3 -- first odd in the segment
-- First odd in the segment.
o = max (a + fromEnum (even a)) 3
r = floor . sqrt $ (fromIntegral b :: Float) + 1
arr =
-- Create a boolean array indexed from o to b;
-- the indices produced by the association list
-- are set to false.
AU.accumArray
(\_ _ -> False) -- accumulating fn
True -- initial value
-- Default value, used when the index
-- is not present in the association list.
True
(o, b) -- bounds of the array
[ (i, ()) -- association list
| p <- [3, 5 .. r],
let q = p * p -- flip every multiple of an odd to False
-- Flip every multiple of an odd to False.
let q = p * p
s = 2 * p
-- Difference between divMod and quotRem.
-- https://stackoverflow.com/a/339823/839733
Expand Down
1 change: 1 addition & 0 deletions test/ArithmeticSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ spec = do
describe "primesR" $ do
it "constructs a list of primes within a given range" $ do
primesR 10 20 `shouldBe` [11, 13, 17, 19]
primesR 7 31 `shouldBe` [7, 11, 13, 17, 19, 23, 29, 31]

describe "goldbach" $ do
it "finds two prime numbers that sum to a given even integer" $ do
Expand Down

0 comments on commit 9fdda15

Please sign in to comment.