Simplify a Fraction

前端 未结 4 859
遥遥无期
遥遥无期 2020-12-17 21:08

How can I simplify a fraction in PHP?

For instance, converting 40/100 to 2/5.

The only way I could think of is to do a prime factor

相关标签:
4条回答
  • 2020-12-17 21:28

    The algorithm is pretty simple:

    • extract both values from a string.
    • find their greatest common divisor ($gcd) (with Euclidean algorithm, for example)
    • divide both values by $gcd
    • rebuild the string with the values found
    0 讨论(0)
  • 2020-12-17 21:29

    Here's a simple recursive PHP function

    
    <?php
    
      function reduceFraction($numerator, $denominator)
      {
        $gcd = findGreatestCommonDenominator($numerator, $denominator);
    
        return [$numerator / $gcd, $denominator / $gcd];
      }
    
    
      function findGreatestCommonDenominator($a, $b)
      {
        return $b ? findGreatestCommonDenominator($b, $a % $b) : $a;
      }
    }
    

    usage :

    
    <?php $reduced = reduceFraction(40,100); // returns [2,5] ?>
    
    0 讨论(0)
  • 2020-12-17 21:33

    If you have PHP gmp extension, you can do this.

    $num = 40;
    $den = 100;
    $gcd = gmp_intval(gmp_gcd((string)$num, (string)$den));
    
    $new_num = $num / $gcd;
    $new_den = $den / $gcd;
    
    0 讨论(0)
  • When you simplify a fraction, you divide the numerator and denominator by their greatest common divisor.

    So all you need is to calcuate the GCD of the two numbers. There's no built-in function for that, but it's easy enough to implement the euclidean algorithm:

    function gcd($a,$b) {
        $a = abs($a); $b = abs($b);
        if( $a < $b) list($b,$a) = Array($a,$b);
        if( $b == 0) return $a;
        $r = $a % $b;
        while($r > 0) {
            $a = $b;
            $b = $r;
            $r = $a % $b;
        }
        return $b;
    }
    

    Then just divide the top and bottom by that.

    function simplify($num,$den) {
        $g = gcd($num,$den);
        return Array($num/$g,$den/$g);
    }
    var_export(simplify(40,100)); // Array(2,5)
    
    0 讨论(0)
提交回复
热议问题