import java.math.*; import javax.imageio.*; import java.awt.image.*; import java.awt.event.*; import java.awt.*; import java.security.spec.*; import java.security.*; import java.lang.management.*; import java.lang.ref.*; import java.lang.reflect.*; import java.net.*; import java.io.*; import javax.swing.table.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.*; import java.util.concurrent.atomic.*; import java.util.concurrent.*; import java.util.regex.*; import java.util.List; import java.util.zip.*; import java.util.*; public class main { static class Rat { BigInteger a, b; Rat() {} // for persistence Rat(BigInteger a, BigInteger b) { this.b = b; this.a = a; simplify(); } Rat(BigInteger a) { this.a = a; b = bigint(1); } Rat(long a) { this(bigint(a)); } Rat(long a, long b) { this(bigint(a), bigint(b)); } Rat multiply(Rat r) { return new Rat(a.multiply(r.a), b.multiply(r.b)); } Rat divide(Rat r) { return 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 String toString() { if (eq(b, 1)) return a.toString(); else return a + "/" + b; } // TODO (maybe): compare with int etc. public boolean equals(Object o) { if (!(o instanceof Rat)) return false; Rat r = (Rat) ( o); return eq(a, r.a) && eq(b, r.b); } } public static void main(String[] args) throws Exception { print("5 = " + new Rat(5)); print("5/4 = " + new Rat(5, 4)); print("10/4 = " + new Rat(10, 4)); print("eq: " + eq(new Rat(10, 4), new Rat(20, 8))); } static boolean eq(Object a, Object b) { if (a == null) return b == null; if (a.equals(b)) return true; if (a instanceof BigInteger) { if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b)); if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b)); } return false; } static StringBuffer print_log; static void print() { print(""); } static void print(Object o) { String s = String.valueOf(o) + "\n"; synchronized(StringBuffer.class) { if (print_log == null) print_log = new StringBuffer(); } print_log.append(s); System.out.print(s); } static void print(long l) { print(String.valueOf(l)); } static BigInteger bigint(String s) { return new BigInteger(s); } static BigInteger bigint(long l) { return BigInteger.valueOf(l); } static boolean equals(Object a, Object b) { return a == null ? b == null : a.equals(b); } }