Posted on by Kalkicode
Code Greedy

Egyptian fraction solution in php

Php program for Egyptian fraction solution. Here more information.

<?php
/*
  Php program for
  Egyptian fraction solution
*/
class Fraction
{
	public	function egyptianFraction($a, $b)
	{
		if ($a == 0 || $b == 0)
		{
			return;
		}
		if ($b >= $a)
		{
			// Calculate remainder
			$remainder = $b % $a;
			// Calculate divisor
			$divisor = (int)($b / $a);
			if ($remainder != 0)
			{
				$divisor++;
				echo "1/",($divisor)," + ";
				$a = $a * $divisor - $b;
				$b = $b * $divisor;
				$this->egyptianFraction($a, $b);
			}
			else
			{
				// When remainder is zero
				echo "1/".strval($divisor);
			}
		}
		else
		{
			// When b < a
			echo ((int)($a / $b))," + ";
			$this->egyptianFraction($a % $b, $b);
		}
	}
	public static
	function main($args)
	{
		$task = new Fraction();
		// Two numbers
		$a = 7;
		$b = 53;
		$task->egyptianFraction($a, $b);
	}
}
Fraction::main(array());

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