You are viewing a single comment's thread. Return to all comments →
what is wrong with this code ....
this code is working fine on my Terminal ...
hugeGcd nListInt mListInt = gcd (product nListInt) (product mListInt)
main :: IO ()
main = do
n <- getLine
nList <- getLine
let nListInt = map read $ words nList :: [Int]
m <- getLine
mList <- getLine
let mListInt = map read $ words mList :: [Int]
putStrLn $ show (hugeGcd nListInt mListInt)
product nListInt will overflow - for example product [1..100 :: Int] will evaluate to 0 - just add in fromIntegral or change Int to Integer and you are good to go
product [1..100 :: Int]
why this happen can you please explane this
ok I'll try - see Int has usually 64bits - but let's make things easier and assume that we have only 4bits - one of these indicates positive or negative so we have 3bits for positive left
Now when you do 1(=001)*2(=010)*3(=011)*4(=100) you already are at 24(=11000) and as you can see this is more that fits the 4 bits (the same is true for 64bits - it just takes more factors)
if you get no overflow protection the higher bits are just truncated (and you will shift out all 1s and end up as GHCi tells you with 0).
On the other hand, if there is protection enabled you get an exception - in both cases you end up with a wrong program
if you switch to Integer the numbers can grow as big as you've got memory for your program (more than enough for this case) and so you don't run into overflows or exceptions here.
WOw , Thanks for this greate and wonderful explanation thanks a lot