Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Rational {
- // the rational number a/b
- private final long a;
- private final long b;
- // class is immutable
- // overloaded constructors
- public Rational(long a, long b) {
- this.a = a;
- this.b = b;
- }
- public Rational(int a, int b) {
- this.a = a;
- this.b = b;
- }
- public Rational(int a)
- {
- this.a=a;
- this.b=1;
- }
- private static Rational lowestForm(long a, long b) {
- long x = a;
- long y = b;
- while (b != 0) {
- long t = b;
- b = a % b;
- a = t;
- }
- return new Rational(x / a, y / a);
- }
- public String toString() {
- return a + "/" + b;
- }
- public Rational add(Rational other) {
- return lowestForm(a * other.b + b * other.a, b * other.b);
- }
- public Rational div(Rational other) {
- return lowestForm(a * other.b, b * other.a);
- }
- }
- public class Test {
- public static void main(String[] args) {
- Rational r1 = new Rational(1);
- Rational r2 = new Rational(1,3);
- Rational r3 = r1.add(r2);
- System.out.println(r3); // 4/3
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment