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... Link to comment https://forums.phpfreaks.com/topic/165934-solved-fraction-simplest-form-anyone/ 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); ?> Link to comment https://forums.phpfreaks.com/topic/165934-solved-fraction-simplest-form-anyone/#findComment-875227 Share on other sites More sharing options...
shamuraq Posted July 15, 2009 Author Share Posted July 15, 2009 Thanx rhodesa... Link to comment https://forums.phpfreaks.com/topic/165934-solved-fraction-simplest-form-anyone/#findComment-875501 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.