Simplify Fraction with Checks

Simplify Fraction with Checks

Medium PHP PHP Error Handling 23 views
Explanation Complexity

Problem Statement

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.

Example

6 8
3 4

Constraints

|a|

Input / Output Format

Input Format
One line: a b.
Output Format
p q or ERROR.
Constraints
|a|

Examples

Input:
6 8
Output:
3 4

Example Solution (Public)

PHP
<?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;
?>

Official Solution Code

<?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;
?>
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.