Design a small value class with its own rules: fractions that always stay in simplest form.
What to build
A program that adds fractions.
Requirements
- Write a class
Fractionwith a numerator and a denominator, anaddmethod that returns a new Fraction, and__toString. - A fraction is always kept in simplest form, and one with denominator 1 prints as just the numerator.
- Read n, then n lines
a b c d. For each, print the sum of a/b and c/d.
Input
Line 1: n. Then n lines of four integers.
Output
n lines.
Constraints
1 ≤ n ≤ 20; 1 ≤ a, b, c, d ≤ 100.
Example
Input:
3
1 2 1 3
1 2 1 2
3 4 5 6
Output:
5/6
1
19/12
Why it works
Simplifying inside the constructor keeps every Fraction object correct, so the printing code stays simple.
Examples
Example 1 · Input
3 1 2 1 3 1 2 1 2 3 4 5 6
Expected output
5/6 1 19/12
Example 2 · Input
2 2 4 3 6 7 10 1 10
Expected output
1 4/5
Hints
Hint 1
Add a/b + c/d as (a*d + c*b) / (b*d), then divide both parts by their greatest common divisor.
Hint 2
Write __toString so that echo prints the fraction, and a whole number without the /1.
Solution
Show one correct solution (try it yourself first)
<?php
class Fraction
{
private int $num;
private int $den;
public function __construct(int $num, int $den)
{
$g = self::gcd($num, $den);
$this->num = intdiv($num, $g);
$this->den = intdiv($den, $g);
}
private static function gcd(int $a, int $b): int
{
return $b === 0 ? $a : self::gcd($b, $a % $b);
}
public function add(Fraction $other): Fraction
{
return new Fraction($this->num * $other->den + $other->num * $this->den, $this->den * $other->den);
}
public function __toString(): string
{
return $this->den === 1 ? (string) $this->num : $this->num . "/" . $this->den;
}
}
$n = (int) trim(fgets(STDIN));
for ($i = 0; $i < $n; $i++) {
fscanf(STDIN, "%d %d %d %d", $a, $b, $c, $d);
echo (new Fraction($a, $b))->add(new Fraction($c, $d)), "\n";
}