Egyptian fraction solution in ruby

Ruby program for Egyptian fraction solution. Here problem description and other solutions.

#  Ruby program for
#  Egyptian fraction solution
class Fraction 
	def egyptianFraction(a, b) 
		if (a == 0 || b == 0) 
			return
		end

		if (b >= a) 
			#  Calculate remainder
			remainder = b % a
			#  Calculate divisor
			divisor = b / a
			if (remainder != 0) 
				divisor += 1
				print("1/", divisor ," + ")
				a = a * divisor - b
				b = b * divisor
				self.egyptianFraction(a, b)
			else
 
				#  When remainder is zero
				print("1/", divisor)
			end

		else
 
			#  When b < a
			print((a / b) ," + ")
			self.egyptianFraction(a % b, b)
		end

	end

end

def main() 
	task = Fraction.new()
	#  Two numbers
	a = 7
	b = 53
	task.egyptianFraction(a, b)
end

main()

Output

1/8 + 1/142 + 1/30104


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved