Try Again

基础知识学习
随笔 - 4, 文章 - 0, 评论 - 0, 引用 - 0
数据加载中……

java 分数类

class Fraction
{
    BigInteger up, down;
    
public Fraction (Fraction f)
    {
        
this.up = f.up;
        
this.down = f.down;
    }
    
public Fraction(String s)
    {
        
this.up = new BigInteger(s);
        
this.down = new BigInteger("1");
    }
    
public Fraction(BigInteger a, BigInteger b)
    {
        
this.up = a;
        
this.down = b;
    }
    
public BigInteger getUp()
    {
        
return this.up;
    }
    
public BigInteger getDown()
    {
        
return this.down;
    }
    
public Fraction subtract(Fraction f)
    {
        BigInteger save1 
= this.up.multiply (f.down);
        BigInteger save2 
= f.up.multiply(this.down);
        Fraction tmp 
= new Fraction(save1.subtract (save2), f.down .multiply ( this.down));
        
return simplex(tmp);
    }
    
public Fraction add(Fraction f)
    {
        Fraction tmp 
= new Fraction ("0");
        tmp 
= tmp.subtract(f);
        Fraction ans 
= new Fraction (this.subtract(tmp));
        
return ans;
    }
    
public Fraction multiply(Fraction f)
    {
        Fraction tmp;
        tmp 
= new Fraction(this.up.multiply (f.up), this.down.multiply (f.down));
        
if (tmp.down.compareTo(new BigInteger("0")) == -1)
        {
            tmp.down 
= tmp.down.multiply (new BigInteger("-1"));
            tmp.up 
= tmp.up.multiply (new BigInteger("-1"));
        }
        
return simplex(tmp);
    }
    
public Fraction divide(Fraction f)
    {
        Fraction tmp 
= null;
        tmp 
= new Fraction(this.up.multiply (f.down), this.down.multiply (f.up));
        
if (tmp.down.compareTo(new BigInteger("0")) == -1)
        {
            tmp.down 
= tmp.down.multiply (new BigInteger("-1"));
            tmp.up 
= tmp.up.multiply (new BigInteger("-1"));
        }
        
return simplex(tmp);
    }
    BigInteger gcd(BigInteger a, BigInteger b)
    {
        
if (b.compareTo(new BigInteger("0")) == 0)
            
return a;
        
return gcd(b, a.remainder (b));
    }
    Fraction simplex(Fraction f)
    {
        BigInteger tmp 
= gcd(f.up.abs(), f.down.abs ());
        f.up 
= f.up.divide (tmp);
        f.down 
= f.down.divide (tmp);
        
return f;
    }
    
void print()
    {
        BigInteger a, b, c;
        a 
= this.getUp ();
        b 
= this.getDown();
        c 
= gcd(a.abs(), b.abs());
        a 
= a.divide (c);
        b 
= b.divide (c);
        
if (b.compareTo (new BigInteger("1")) == 0)
            System.out.println(a);
        
else
            System.out.println (a 
+ "/" + b);
    }
}

posted on 2009-03-08 21:02 NicYun 阅读(563) 评论(0)  编辑 收藏 引用 所属分类: Algorithm


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理