0
public function add($temp) {
        $newNum = $this->num + $temp->num;
        if($this->denum == $temp->denum) {
               // add two fractions having same denominator
               $answer = $newNum . "/" . $this->denum;
        } else {
               // how to add two fractions having different denominator?
        }
        return $answer;
}

In other words, how to handle the case of two fractions having different denominators, like:

1/3 + 1/6 = 3/6

or

1/3 + 1/5 = 8/15

RandomSeed
  • 29,301
  • 6
  • 52
  • 87
JeraldPunx
  • 309
  • 3
  • 8
  • 18

3 Answers3

3
function gcd($num1, $num2) {
 /* finds the greatest common factor between two numbers */
    if ($num1 < $num2) {
        $t = $num1;
        $num1 = $num2;
        $num2 = $t;
    }
    while ($t = ($num1 % $num2) != 0) {
        $num1 = $num2;
        $num2 = $t;
    }
    return $num2;
}

public function add($temp) {
    $newNum = $this->num * $temp->denum + $temp->num * $this->denum;
    $newDenum = $temp->denum * $this->denum;
    $gcd = gcd($newNum, $newDenum);
    $newNum /= $gcd;
    $newDenum /= $gcd;
    return $newNum . '/' . $newDenum;
}
jhdxr
  • 166
  • 1
  • 4
0

Let's say you want to add 1/3 to 1/6, you simply do

$result = 1/3 + 1/6;
DusteD
  • 1,400
  • 10
  • 14
0

This won't reduce fractions for you, but other than that it should do what you want:

public function add($temp) {
    if($this->denum == $temp->denum) {
        $newNum = $this->num + $temp->num;
        $answer = $newNum . "/" . $this->denum;
    } else {
        $newNum = $this->num * $temp->denum + $temp->num * $this->denum;
        $answer = $newNum . "/" . $this->denum*$temp->denum;
    }
    return $answer;
}
John V.
  • 4,652
  • 4
  • 26
  • 26