package heap;
public class Rational{
protected int num;
protected int den;
public Rational(){
num = 0;
den = 1;
}
public boolean equals(Object obj){
if (obj instanceof Rational){
Rational rat= (Rational) obj;
return this.num==rat.num && this.den==rat.den;
}
return false;
}
public Rational(int n,int d){
num = n;
den = d;
}
public float toFloat(){
return ((float) num/den);
}
public String toString(){
if (den != 1)
return num + "/" + den;
else
return String.valueOf(num);
}
public void simplify(){
int gcd = ints.Arithmetic.gcd(num,den);
num = num/gcd;
den = den/gcd;
}
public Rational simplify2(){
int outNum = num;
int outDen = den;
int gcd = ints.Arithmetic.gcd(outNum,outDen);
outNum = outNum/gcd;
outDen = outDen/gcd;
return new Rational(outNum,outDen);
}
public Rational exp(int e){
int outNum = ints.Arithmetic.exp(num,e);
int outDen = ints.Arithmetic.exp(den,e);
return new Rational(outNum,outDen);
}
public Rational add(Rational r){
Rational out;
int commonDen = ints.Arithmetic.lcm(den,r.den);
out = new Rational(commonDen/den*num + commonDen/r.den*r.num,commonDen);
return out;
}
/*
public Rational add(Rational r){
int outDen = this.den * r.den;
int outNum = (this.num * r.den) + (this.den * r.num);
return new Rational(outNum,outDen);
}
*/
public Rational mul(Rational r){
return new Rational(num * r.num,den * r.den);
}
public Rational div(Rational r){
return new Rational(num * r.den,den * r.num);
}
public static Rational test(){
Rational r1 = new Rational(0,0);
return r1.simplify2();
}
public static void arraycopy(Object[] src,int srcPos,Object[] dest,int destPos,int length){
if (length < 0) throw new ArithmeticException();//ArrayIndexOutOfBoundsException();
for (int i = 0; i < length; i++)
dest[destPos+i] = src[srcPos+i];
}
public static void arraycopy(Object[] src,Object[] dest,int length){
if (length < 0) throw new ArithmeticException();//ArrayIndexOutOfBoundsException();
for (int i = 0; i < length; i++)
dest[i] = src[i];
}
public static Rational[] foo(Rational[] rs){
int length = rs.length;
Rational[] oldRs = new Rational[length];
arraycopy(rs,oldRs,length);
for (int i = 0;i < length;i++)
rs[i].simplify();
return oldRs;
}
private static void printArray(Rational[] rs){
for (int i = 0;i < rs.length;i++)
System.out.print(rs[i].toString() + " ");
System.out.println();
}
public static void main(String[] args){
Rational r0 = new Rational(5,10);
Rational r1 = new Rational(2,10);
Rational r2 = new Rational(4,6);
Rational[] rs = new Rational[3];
rs[0] = r0; rs[1] = r1; rs[2] = r2;
System.out.print("Original array: ");
printArray(rs);
Rational[] oldRs = foo(rs);
System.out.print("Simplified array: ");
printArray(rs);
System.out.print("Copied array: ");
printArray(oldRs);
}
/*
public static void main(String[] args){
Rational r1 = new Rational(10,20);
Rational r2 = new Rational(5,10);
r1.simplify();
r2.simplify();
Rational r3 = r1.exp(2);
Rational r4 = r3.add(r2);
System.out.println(r4);
}
*/
}
|