Coding with your own knowledge to learn about algorithms. Day 1 I don't know if it will continue
One of the most famous algorithms. No more explanation needed. Finding the greatest common divisor for two natural numbers a and b. The method finds the remainders of a and b. Next, b and the remainder of the remainder are obtained. Then, the remainder of the surplus and the surplus of the surplus of the surplus are obtained. The divisor when repeated until the remainder becomes 0 is the common divisor of a and b.
Once you understand how it works, code it immediately
Euclid.rb
def euclid(a, b)
while b != 0
mod = a % b
a = b
b = mod
end
a
end
print "Value of a:"
a = gets.to_i
print "value of b:"
b = gets.to_i
puts "The greatest common divisor of a and b is#{euclid(a,b)}is"
Enter a and b and use them as method arguments.
Substitute the remainder of a and b for mod Substitute b for a Substitute mod for b
Repeat this only when b is greater than 0
Probably no problem
It's a simple code so there should be no mistake What we want from experts -Code simplification ・ Reduction of processing speed I don't know if it's feasible because I've come up with it, but thank you.
Tomorrow we will implement bubble sort.
Recommended Posts