Simplify Fraction with Checks
PHP
Medium
5 views
Problem Description
Input a b meaning a/b. If b=0 print ERROR. Else print reduced fraction p q.
Input Format
One line: a b.
Output Format
p q or ERROR.
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
[$a,$b]=array_map('intval',preg_split('/\\s+/', $inputText));
if($b===0){ echo 'ERROR'; exit; }
function gcd3($x,$y){
$x=abs($x); $y=abs($y);
while($y!==0){ $t=$x%$y; $x=$y; $y=$t; }
return $x;
}
$g=gcd3($a,$b);
$a=intdiv($a,$g);
$b=intdiv($b,$g);
if($b<0){ $a=-$a; $b=-$b; }
echo $a.' '.$b;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!