سؤال

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
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top