[Haskell-beginners] Prime number test performance on negative integers

Folsk Pratima folsk0pratima at cock.li
Mon Dec 11 17:24:17 UTC 2023


Please explain why this fails for negative numbers. By fails I mean it
starts eating RAM infinitely until either me or OOM kills it. If you
replace `m1` definition with the one commented out, the code will fail
for positive integers as well, which is very frustrating.

import System.Environment

isPrime :: Int -> (Bool, String)
isPrime n =
    let ll n = k + 1 : k + 5 : ll (n + 1)
          where
            k = 6 * n + 1
        l = 2 : 3 : 5 : ll 1
        q (i:is)
            | i * i > n = (True, "it is")
            | (n `rem` i) == 0 = (False, "divisible by " ++ show i)
            | otherwise = q is
     in q l

main =
    getArgs >>= \argv ->
        let f True = "primal"
            f False = "not primal"
            m0 = map (\x -> read x :: Int) argv
            m1 = m0
            --m1 =
            --    map
            --        (\x ->
            --             if x < 0
            --                 then -x
            --                 else x)
            --        m0
            m2 = map isPrime m1
            msg (x, (y0, y1)) = x ++ " is " ++ f y0 ++ " because " ++ y1
         in mapM_ putStrLn $ map msg (zip argv m2)


More information about the Beginners mailing list