Simplify a Fraction

前端 未结 4 871
遥遥无期
遥遥无期 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

提交回复
热议问题