shamuraq Posted July 14, 2009 Share Posted July 14, 2009 Hey all, Scenario: $a = rand(1,20); $b = rand(20,30); //since there's no way to express fraction as integer $c = "$a"."/"."$b"; How do i express the fraction in simplest form? Thanx all in advance... Quote Link to comment Share on other sites More sharing options...
rhodesa Posted July 14, 2009 Share Posted July 14, 2009 For larger numerator/denominator values, this might be a little slow. But most cases it should be fine: <?php function gcd($num1, $num2) { while ($num2 != 0){ $t = $num1 % $num2; $num1 = $num2; $num2 = $t; } return $num1; } $a = rand(1,20); $b = rand(20,30); printf('Before: %d/%d<br />',$a,$b); $gcd = gcd($a,$b); printf('After: %d/%d<br />',$a/$gcd,$b/$gcd); ?> Quote Link to comment Share on other sites More sharing options...
shamuraq Posted July 15, 2009 Author Share Posted July 15, 2009 Thanx rhodesa... Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.