patternrubyModerate
GCD of two numbers in Ruby
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)
endSolution
It does not matter whether
Check also Integer#gcd.
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))
endCheck also Integer#gcd.
Code Snippets
def gcd(a, b)
b == 0 ? a : gcd(b, a.modulo(b))
endContext
StackExchange Code Review Q#140620, answer score: 15
Revisions (0)
No revisions yet.