Egyptian fraction solution in scala

Scala program for Egyptian fraction solution. Here more information.

/*
  Scala program for
  Egyptian fraction solution
*/
class Fraction()
{
	def egyptianFraction(a: Int, b: Int): Unit = {
		if (a == 0 || b == 0)
		{
			return;
		}
		if (b >= a)
		{
			// Calculate remainder
			var remainder: Int = b % a;
			// Calculate divisor
			var divisor: Int = b / a;
			if (remainder != 0)
			{
				divisor += 1;
				print("1/" + divisor + " + ");
				egyptianFraction(a * divisor - b, b * divisor);
			}
			else
			{
				// When remainder is zero
				print("1/" + divisor);
			}
		}
		else
		{
			// When b < a
			print(""+ (a / b) + " + ");
			egyptianFraction(a % b, b);
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: Fraction = new Fraction();
		// Two numbers
		var a: Int = 7;
		var b: Int = 53;
		task.egyptianFraction(a, b);
	}
}

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