summaryrefslogtreecommitdiff
path: root/test/files/pos/Rational.scala
blob: 14236975d4ec4936a95aac2f317d6aed8913dfaa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Rational(x: Int, y: Int) {
  private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b);
  private def g = gcd(x, y);
  def numer = x / g;
  def denom = y / g;
  def add(r: Rational) =
    new Rational(
      numer * r.denom + r.numer * denom,
      denom * r.denom);
  def sub(r: Rational) =
    new Rational(
      numer * r.denom - r.numer * denom,
      denom * r.denom);
  def mul(r: Rational) =
    new Rational(
      numer * r.numer,
      denom * r.denom);
  def equal(r: Rational) =
    new Rational(
      numer * r.denom,
      denom * r.numer);

  def asString: String = numer + "/" + denom;
  override def toString(): String = numer + "/" + denom
}