Home > other >  Greatest common divisor of three numbers in Haskell
Greatest common divisor of three numbers in Haskell

Time:02-20

So there is gcd for two numbers, which i know how do define.

gcd a 0 = a

gcd a b = gcd b (a `mod` b)

gcd a b c = gcd3 

How could i define a gcd3 for finding the greatest divisor for three numbers. The definition of gcd3 is:

gcd3 :: Int -> Int -> Int -> Int

CodePudding user response:

You can use foldr1 for any count of numbers as:

gcdN = foldr1 gcd

Then we can use as:

gcdN [2, 4, 8, 12]

The output will be:

2

CodePudding user response:

You can take the gcd of three numbers the same way you take the sum of three numbers: by doing it two at a time.

gcd3 :: Int -> Int -> Int -> Int
gcd3 x y z = (x `gcd` y) `gcd` z

CodePudding user response:

Well, if you already know how to find the GCD of two numbers, you can find the GCD of any amount of numbers:

gcd3 a b c = gcd a (gcd b c)

gcd4 a b c d = gcd a (gcd3 b c d)
-- Which is the same as
gcd4 a b c d = gcd a (gcd b (gcd c d))

And so on

  • Related