user335129
user335129

Reputation: 44

Haskell greatest common divisor error?

I want to compute the greatest common divisor of two positive integer numbers in Haskell:

myGCD :: Integer -> Integer -> Integer
myGCD a b
      | b == 0     = abs a
      | otherwise  = myGCD b (b `mod` a)

This should be a fairly simple algorithm. However, I find that I am getting some very strange results. I just can't seem to find an error in the above logic. Anything obvious stand out that would affect computing the greatest common divisor of a and b?

Upvotes: 1

Views: 293

Answers (1)

user6269144
user6269144

Reputation: 318

You are almost right! You mised up a call to myGCD. The correct code should read:

myGCD :: Integer -> Integer -> Integer
myGCD a b
      | b == 0     = abs a
      | otherwise  = myGCD b (a `mod` b)

Reversing the order of a and b in that last line will give you some funky results!

Upvotes: 3

Related Questions