Posted on by Kalkicode
Code Greedy

Egyptian fraction solution in node js

Js program for Egyptian fraction solution. Here more information.

/*
  Node JS program for
  Egyptian fraction solution
*/
class Fraction
{
	egyptianFraction(a, b)
	{
		if (a == 0 || b == 0)
		{
			return;
		}
		if (b >= a)
		{
			// Calculate remainder
			var remainder = b % a;
			// Calculate divisor
			var divisor = parseInt(b / a);
			if (remainder != 0)
			{
				divisor++;
				process.stdout.write("1/" + divisor + " + ");
				a = a * divisor - b;
				b = b * divisor;
				this.egyptianFraction(a, b);
			}
			else
			{
				// When remainder is zero
				process.stdout.write("1/" + divisor);
			}
		}
		else
		{
			// When b < a
			process.stdout.write((parseInt(a / b)) + " + ");
			this.egyptianFraction(a % b, b);
		}
	}
}

function main()
{
	var task = new Fraction();
	// Two numbers
	var a = 7;
	var b = 53;
	task.egyptianFraction(a, b);
}
// Start program execution
main();

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