Skip to main content

Egyptian fraction solution in c#

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

// Include namespace system
using System;
/*
  Csharp program for
  Egyptian fraction solution
*/
public class Fraction
{
	public void egyptianFraction(int a, int b)
	{
		if (a == 0 || b == 0)
		{
			return;
		}
		if (b >= a)
		{
			// Calculate remainder
			var remainder = b % a;
			// Calculate divisor
			var divisor = (int)(b / a);
			if (remainder != 0)
			{
				divisor++;
				Console.Write("1/" + divisor + " + ");
				a = a * divisor - b;
				b = b * divisor;
				this.egyptianFraction(a, b);
			}
			else
			{
				// When remainder is zero
				Console.Write("1/" + divisor.ToString());
			}
		}
		else
		{
			// When b < a
			Console.Write(((a / b)) + " + ");
			this.egyptianFraction(a % b, b);
		}
	}
	public static void Main(String[] args)
	{
		var task = new Fraction();
		// Two numbers
		var a = 7;
		var b = 53;
		task.egyptianFraction(a, b);
	}
}

Output

1/8 + 1/142 + 1/30104




Comment

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