Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package lab5;
- class Rational {
- ///////////////////////////////utilities/////////////////////////////
- int NWD(int a, int b)
- { if(a==0)
- {
- return 1;
- }
- int c = a;
- int d = b;
- while (c != d)
- {
- if (c>d)
- {
- c -= d;
- }
- else
- {
- d -= c;
- }
- }
- return c;
- }
- ////////////////////////////////////fields////////////////////////////////
- private int l = 0, m = 0, c = 0;
- ////////////////////////constructors//////////////////////////////////////
- Rational (int a, int b)
- {
- l = a;
- m = b;
- }
- Rational ( int a)
- {
- this (a,1);
- }
- ////////////////////////methods/////////////////////////
- Rational short_rat()
- { if (l ==0)
- {
- return this;
- }
- int nwd = NWD(l, m);
- l = l/nwd;
- m = m/nwd;
- c = l/m;
- if (c != 0)
- {
- l = l-c*m;
- }
- return this;
- }
- Rational addition (Rational b)
- {
- return new Rational (l*b.m + m*b.l, m*b.m );
- }
- Rational substraction (Rational b)
- {
- return new Rational (l*b.m - m*b.l, m*b.m );
- }
- Rational multipli (Rational b)
- {
- return new Rational (l*b.l, m*b.m );
- }
- Rational reverse()
- {
- return new Rational (m,l);
- }
- Rational divide (Rational b)
- {
- return new Rational (l*b.m, m*b.l);
- }
- public String toString()
- {
- short_rat();
- if (c == 0 && l != 0)
- {
- return l+"/"+m;
- }
- else if (l == 0 && c == 0 )
- {
- return Integer.toString(0);
- }
- else if (c != 0 && l == 0)
- {
- return Integer.toString(c);
- }
- else
- {
- return c+" "+l+"/"+m;
- }
- }
- }
- public class Lab5 {
- public static void main(String[] args) {
- Rational x = new Rational(1,2);
- Rational y = new Rational(3,4);
- Rational z = new Rational(3,4);
- Rational a = new Rational(5,6);
- System.out.println(x.addition(y).divide(z.substraction(a)).short_rat());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement