diff --git a/src/Arithmetic.hs b/src/Arithmetic.hs index dd128d1..b68d1ef 100644 --- a/src/Arithmetic.hs +++ b/src/Arithmetic.hs @@ -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 diff --git a/test/ArithmeticSpec.hs b/test/ArithmeticSpec.hs index d2cbd59..1c63333 100644 --- a/test/ArithmeticSpec.hs +++ b/test/ArithmeticSpec.hs @@ -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