java大数

来源:互联网 发布:手机数据圈论坛 编辑:程序博客网 时间:2024/05/22 13:19

题目意思:求很多个分数的和。http://acm.hnu.cn/online/?action=problem&type=show&id=13085&courseid=293

超long long

Fun With FractionsTime Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:32768KBTotal submit users: 4, Accepted users: 4Problem 13085 : No special judgementProblem description


Input


Output

Output should consist of one line for each test comprising the test number (formatted as shown) followed by a single space and the sum of the input number sequence. The sum should be displayed in lowest terms using mixed number format. If either the whole number part or the fractional part is zero, that part should be omitted. As a special case, if both parts are zero, the value should be displayed as a single 0.


Sample Input
21/21/331/32/63/9312/34,5/60
Sample Output
Test 1: 5/6Test 2: 1Test 3: 6,1/2
import java.math.BigInteger;import java.util.Scanner;public class gcd {static BigInteger a,b,c,d;static BigInteger zero = new BigInteger("0");static BigInteger one = new BigInteger("1");static BigInteger ten = new BigInteger("10");public static void getnum(String s){    BigInteger n= zero,fz=zero,fm=zero;    String str;    int len=s.length();    int i=0;    str="";    while(i<len&&s.charAt(i)!=','&&s.charAt(i)!='/'){    str=str+s.charAt(i);                i++;    }    if(i==len){        fz=new BigInteger(str);        fm=new BigInteger("1");    }    else if(s.charAt(i)=='/'){        fz=new BigInteger(str);        i++;        str="";        while(i<len){            str = str + s.charAt(i);            i++;        }        fm=new BigInteger(str);    }else {    n = new BigInteger(str);        i++;        str="";        while(s.charAt(i)!='/'){        str = str + s.charAt(i);            i++;        }        fz = new BigInteger(str);        i++;        str="";        while(i<len){        str = str + s.charAt(i);            i++;        }        fm = new BigInteger(str);        fz=n.multiply(fm).add(fz);    }    BigInteger g = fz.gcd(fm);    c=fz.divide(g);    d=fm.divide(g);}public static void merge(){    BigInteger fz=(a.multiply(d)).add(b.multiply(c));    BigInteger fm=b.multiply(d);    BigInteger g = fz.gcd(fm);    a=fz.divide(g);    b=fm.divide(g);}public static void out(){if(b.equals(one)){System.out.println(a);}else if(a.equals(b)){System.out.println("1");}    else if(a.compareTo(b)<0){System.out.println(a+"/"+b); }    else if(a.compareTo(b)>0){System.out.println(a.divide(b)+","+a.mod(b)+"/"+b);}    return ;}public static void main(String args[])     {int T=1;    Scanner cin = new Scanner(System.in);    while(true){    int n=cin.nextInt();    if(n==0)return ;    for(int i=0;i<n;i++){    String s = cin.next();                if(i==0){                getnum(s);                a=c;                b=d;                }                else{                    getnum(s);                    merge();                }    }    System.out.print("Test "+T+": ");    out();    T++;    }    }}



0 0