Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Rational extends Number implements Comparable<Rational> {
- public double doubleValue(){
- return (double)num1 / (double)den1;
- }
- public float floatValue(){
- return (float)num1 / (float)den1;
- }
- public int intValue(){
- return num1 / den1;
- }
- public long longValue(){
- return (long)num1 / (long)den1;
- }
- public int compareTo(Rational o){
- if (num1 * o.den1 < o.num1 * den1){
- return 1;
- }
- else if (num1 * o.den1 > o.num1 * den1){
- return -1;
- }
- else{
- return 0;
- }
- }
- public Rational(int n1, int d1) {
- num1 = n1;
- den1 = d1;
- }
- public Rational add(Rational o) {
- int n1 = num1 * o.den1+ o.num1 * den1;
- int d1 = den1 * o.den1;
- return new Rational(n1 / gcd (n1, d1), d1/ gcd (n1,d1));
- }
- public Rational sub(Rational o) {
- int n1 = num1 * o.den1 - o.num1 * den1;
- int d1 = den1 * o.den1;
- return new Rational( n1 / gcd (n1, d1), d1 / gcd (n1, d1) );
- }
- public Rational mul(Rational o) {
- int n1 = num1 * o.num1;
- int d1 = den1 * o.den1;
- return new Rational( n1/ gcd (n1,d1), d1 / gcd (n1, d1));
- }
- public Rational div(Rational o) {
- int totalx = (num1 * o.den1);
- int totaly = (den1 * o.num1);
- return new Rational (totalx / gcd (totalx , totaly), totaly / gcd
- (totalx, totaly));
- }
- int gcd(int num1, int den1){
- int r, x;
- while (den1 != 0) {
- x = den1;
- r = (num1 % den1);
- den1 = r;
- num1 = x;
- }
- return num1;
- }
- public String toString() {
- if (den1 != 0)
- return "(" + num1 + " / " + den1 + ")";
- else
- return ("Undefined");
- }
- private int num1;
- private int den1;
- /*public static void main(String[] args) {
- Rational a = new Rational(1, 14);
- Rational b = new Rational(1, 30);
- System.out.println(a + " + " + b + " = " + a.add(b));
- System.out.println(a + " - " + b + " = " + a.sub(b));
- System.out.println(a + " * " + b + " = " + a.mul(b));
- System.out.println(a + " / " + b + " = " + a.div(b));
- }*/
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement