简化分数 [英] Simplify a Fraction

查看:92
本文介绍了简化分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何简化PHP的一部分?

How can I simplify a fraction in PHP?

例如,将40/100转换为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.

推荐答案

简化分数时,将分子和分母除以它们的最大公约数.

When you simplify a fraction, you divide the numerator and denominator by their greatest common divisor.

因此,您所需要做的就是计算两个数字的GCD.它没有内置功能,但是很容易实现欧几里得算法:

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)

这篇关于简化分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆