Last active
June 2, 2016 08:13
-
-
Save dannycjones/4d95edbb52de37abcb4bc98285ccaba9 to your computer and use it in GitHub Desktop.
An implementation of Euclid's algorithm in Ruby finding the highest common factor for two numbers.
This file contains hidden or 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
def euclids(a, b) # Euclid's Algorithm | |
quotient = a / b | |
remainder = a % b # modulo | |
puts "#{a} = #{quotient}(#{b}) + #{remainder} [hcf(#{a}, #{b})]" | |
return b if remainder.zero? | |
euclids(b, remainder) | |
end | |
def hcf(a, b) | |
euclids(a, b) | |
end | |
begin | |
num1 = ARGV[0].chomp.to_i | |
num2 = ARGV[1].chomp.to_i | |
puts "\nhcf(#{num1}, #{num2}) = #{hcf(num1, num2)}" | |
rescue | |
puts "Invalid arguments given!" | |
puts "euclids.rb <num1> <num2>" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment