Egyptian fraction solution in swift

Swift program for Egyptian fraction solution. Here more information.

import Foundation
/*
  Swift 4 program for
  Egyptian fraction solution
*/
class Fraction
{
	func egyptianFraction(_ a: Int, _ b: Int)
	{
		if (a == 0 || b == 0)
		{
			return;
		}
		if (b >= a)
		{
			// Calculate remainder
			let remainder: Int = b % a;
			// Calculate divisor
			var divisor: Int = b / a;
			if (remainder  != 0)
			{
				divisor += 1;
				print("1/" + String(divisor), terminator: " + ");
				
				self.egyptianFraction(a * divisor - b, b * divisor);
			}
			else
			{
				// When remainder is zero
				print("1/" + String(divisor), terminator: "");
			}
		}
		else
		{
			// When b < a
			print((a / b) , terminator: " + ");
			self.egyptianFraction(a % b, b);
		}
	}
	static func main(_ args: [String])
	{
		let task: Fraction = Fraction();
		// Two numbers
		let a: Int = 7;
		let b: Int = 53;
		task.egyptianFraction(a, b);
	}
}
Fraction.main([String]());

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