Created
November 3, 2013 19:35
-
-
Save AndreasHassing/7293884 to your computer and use it in GitHub Desktop.
Find greatest common divisor - ruby class (Euclid algorithm)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Finds greatest common divisor from 2 digits parsed from console | |
# Usage: ruby gcd.rb 5 2 | |
# Finds the greatest common divisor from the digits 5 and 2 | |
class GCD | |
$digits = Array.new | |
def initialize(args) | |
if args.length == 2 | |
args.each do |a| | |
if a.match(/^\d+$/) | |
$digits.push(a.to_i) | |
else | |
error_message(2) | |
return 2 | |
end | |
end | |
else | |
error_message(1) | |
return 1 | |
end | |
find_gcd($digits) | |
end | |
def find_gcd(digits) | |
a = digits[0] | |
b = digits[1] | |
if b == 0 | |
print 'The greatest common divisor for ' + $digits[0].to_s + ' and ' + $digits[1].to_s + ' is: ' | |
print a.to_s | |
else | |
if a > b | |
a = a - b | |
find_gcd([a, b]) | |
elsif a <= b | |
b = b - a | |
find_gcd([a, b]) | |
end | |
end | |
end | |
def error_message(id) | |
print 'Error: ' | |
case id | |
when 1 # The amount of arguments is less or more than 2 | |
print 'Please parse 2 integers as arguments.' | |
when 2 # One of the arguments is not a valid digit | |
print 'One of the arguments is not a number.' | |
else print 'an undefined error has occurred...' | |
end | |
end | |
end | |
main = GCD.new(ARGV) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment