HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyModerate

GCD of two numbers in Ruby

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
gcdtworubynumbers

Problem

I am trying to implement a algorithm for the GCD of two numbers in a functional approach. Can this be improved further, also with regards to performance?

def gcd(a, b)
   return b if a ==0
   return a if b == 0
   return b if (a%b == 0)
   return a if (b%a == 0)
  (a > b)? gcd(a, a%b) : gcd(b%a, b)
end

Solution

It does not matter whether a > b or b > a, two cases should be enough for positive integers:

def gcd(a, b)
  b == 0 ? a : gcd(b, a.modulo(b))
end


Check also Integer#gcd.

Code Snippets

def gcd(a, b)
  b == 0 ? a : gcd(b, a.modulo(b))
end

Context

StackExchange Code Review Q#140620, answer score: 15

Revisions (0)

No revisions yet.