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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
Then just divide the top and bottom by that.