Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify a Fraction

Tags:

php

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 factorization on both numbers and compare like results, but I'm not really sure how to do that either.

like image 388
Steve Robbins Avatar asked Sep 13 '12 18:09

Steve Robbins


People also ask

Why do we simplify fraction?

We simplify fractions because it is always to work or calculate when the fractions are in the simplest form.


2 Answers

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)
like image 79
Niet the Dark Absol Avatar answered Nov 15 '22 19:11

Niet the Dark Absol


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;
like image 32
Mike Brant Avatar answered Nov 15 '22 20:11

Mike Brant