5

I've adapted this from an example that I found on the 'net...

function ratio($a, $b) {
    $_a = $a;
    $_b = $b;

    while ($_b != 0) {

        $remainder = $_a % $_b;
        $_a = $_b;
        $_b = $remainder;   
    }

    $gcd = abs($_a);

    return ($a / $gcd)  . ':' . ($b / $gcd);

}

echo ratio(9, 3); // 3:1

Now I want it to use func_get_args() and return the ratios for multiple numbers. It looks like a recursive problem, and recursion freaks me out (especially when my solutions infinitely loop)!

How would I modify this to take as many parameters as I wanted?

Thanks

alex
  • 479,566
  • 201
  • 878
  • 984
  • take it from c answer : http://stackoverflow.com/questions/527860/calculate-a-ratio-in-c – Haim Evgi Aug 10 '10 at 10:42
  • What do you mean with 'the ratios for multiple numbers'? Something like `2 : 3 : 5`? What you could do is first compute the prime factorizations for each item in the list of numbers. The product of the prime factors in the intersection is the greatest common denominator. The respective ratios are then computed just like in your example. – Jochem Schulenklopper Aug 10 '10 at 10:45

1 Answers1

7

1st, try this gcd function http://php.net/manual/en/function.gmp-gcd.php Or else you must define a gcd function like

    function gcd($a, $b) {
        $_a = abs($a);
        $_b = abs($b);

        while ($_b != 0) {

            $remainder = $_a % $_b;
            $_a = $_b;
            $_b = $remainder;   
        }
        return $a;
    }

Then modify the ratio function

    function ratio()
    {
        $inputs = func_get_args();
        $c = func_num_args();
        if($c < 1)
            return ''; //empty input
        if($c == 1)
            return $inputs[0]; //only 1 input
        $gcd = gcd($input[0], $input[1]); //find gcd of inputs
        for($i = 2; $i < $c; $i++) 
            $gcd = gcd($gcd, $input[$i]);
        $var = $input[0] / $gcd; //init output
        for($i = 1; $i < $c; $i++)
            $var .= ':' . ($input[$i] / $gcd); //calc ratio
        return $var; 
    }
Bang Dao
  • 5,091
  • 1
  • 24
  • 33