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
user782220
  • 10,677
  • 21
  • 72
  • 135
  • 2
    Could be integer overflow? Have you tried typing `smallFactor` to work with `Integer` types (instead of `Int` which may overflow...). – user268396 Oct 15 '13 at 23:51
  • Duplicates (years old) of this problem: http://stackoverflow.com/q/20700233/3088138, http://stackoverflow.com/q/6544573/3088138 – Lutz Lehmann Mar 08 '14 at 11:38

2 Answers2

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
Thomas M. DuBuisson
  • 64,245
  • 7
  • 109
  • 166
  • 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? – user782220 Oct 16 '13 at 00:02
  • 1
    Luqui covered tihs. If you still have questions after seeing luqui's answer then feel free to post another comment to either of us. – Thomas M. DuBuisson Oct 16 '13 at 03:14
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.

luqui
  • 59,485
  • 12
  • 145
  • 204