public function testGcd() { $this->assertEquals(4, Math::gcd(8, 12)); $this->assertEquals(4, Math::gcd(12, 8)); $this->assertEquals(1, Math::gcd(12, 7)); // Edge cases $this->assertEquals(5, Math::gcd(0, 5)); $this->assertEquals(0, Math::gcd(0, 0)); $this->assertEquals(-2, Math::gcd(2, -2)); $this->assertEquals(2, Math::gcd(-2, -2)); }
/** * Normalize, i.e. make sure the denominator is positive and that * the numerator and denominator have no common factors */ private function normalize() { $gcd = Math::gcd($this->p, $this->q); if ($gcd == 0) { throw new DivisionByZeroException(); } $this->p = $this->p / $gcd; $this->q = $this->q / $gcd; if ($this->q < 0) { $this->p = -$this->p; $this->q = -$this->q; } }