Why is division producing a negative number?
Asked Answered
T

2

5

Why is this printing the negative number -147982099 instead of 8462696833 = 600851475143 / 71

import Data.List

smallFactor n = case (elemIndex 0 (map (mod n) [2..])) of
                    Just x -> x + 2

main = print( quot n (smallFactor n) )
    where n = 600851475143

The full output:

$ ghc --make p3; ./p3
[1 of 1] Compiling Main             ( p3.hs, p3.o )
Linking p3 ...
-147982099
Taunt answered 15/10, 2013 at 23:44 Comment(2)
Could be integer overflow? Have you tried typing smallFactor to work with Integer types (instead of Int which may overflow...).Interpret
Duplicates (years old) of this problem: https://mcmap.net/q/1920847/-empty-list-on-recursive-function/3088138, https://mcmap.net/q/1920848/-project-euler-problem-3-in-haskell/3088138Grantee
L
11

Because you are telling it a negative number (assuming you are using a 32 bit GHC).

where n = 600851475143 -- n = -443946297

notice:

Prelude Data.Int> 600851475143 :: Int32
-443946297
Lucretialucretius answered 15/10, 2013 at 23:52 Comment(2)
So how does Haskell determine what integer type to infer to use given that quot :: Integral a => a -> a -> a and smallFactor :: Integral a => a -> Int are polymorphic?Taunt
Luqui covered tihs. If you still have questions after seeing luqui's answer then feel free to post another comment to either of us.Lucretialucretius
R
11

Haskell usually defaults to Integer when there is a free choice of integral type to use. But here we are seeing Int. And the reason is:

elemIndex :: Eq a => a -> [a] -> Maybe Int

So x in Just x -> x + 2 is an Int, which means smallFactor has to return an Int, which means n in main has to be an Int because quot :: Integral a => a -> a -> a.

This is a good reason to use explicit type signatures.

Ribbonwood answered 16/10, 2013 at 0:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.