static class Rat { BigInteger a, b; *() {} // for persistence *(BigInteger *a, BigInteger *b) { simplify(); } *(BigInteger *a, BigInteger *b, bool simplify) { if (simplify) simplify(); } *(BigInteger *a) { b = bigint(1); } *(long a) { this(bigint(a)); } *(long a, long b) { this(bigint(a), bigint(b)); } Rat multiply(BigInteger i) { ret multiply(new Rat(i)); } Rat divide(BigInteger i) { ret divide(new Rat(i)); } Rat multiply(Rat r) { ret new Rat(a.multiply(r.a), b.multiply(r.b)); } Rat divide(Rat r) { ret new Rat(a.multiply(r.b), b.multiply(r.a)); } void simplify() { // TODO: does this work for negative fractions (especially negative b)? BigInteger gcd = a.gcd(b); if (!eq(gcd, 1)) { a = a.divide(gcd); b = b.divide(gcd); } } public S toString() { if (eq(b, 1)) ret a.toString(); else ret a + "/" + b; } // toString, return as mixed number if applicable // todo: negatives public S mixed() { if (a.compareTo(b) > 0 && neq(b, 1)) { BigInteger rest = a.mod(b); BigInteger whole = a.divide(b); ret whole + "+" + rest + "/" + b; } ret toString(); } // TODO (maybe): compare with int etc. public boolean equals(O o) { if (!(o instanceof Rat)) ret false; Rat r = cast o; ret eq(a, r.a) && eq(b, r.b); } }