1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader br= new BufferedReader( new InputStreamReader(System.in)); String[] str=(br.readLine()).split( " " ); String[] str1=str[ 0 ].split( "/" ); String[] str2=str[ 1 ].split( "/" ); int a1=Integer.parseInt(str1[ 0 ]); int b1=Integer.parseInt(str1[ 1 ]); int a2=Integer.parseInt(str2[ 0 ]); int b2=Integer.parseInt(str2[ 1 ]); add(a1,b1,a2,b2); minus(a1,b1,a2,b2); multi(a1,b1,a2,b2); div(a1,b1,a2,b2); } private static void add( int a1, int b1, int a2, int b2) { int x=a1*b2+a2*b1; int y=b1*b2; printSimple(a1,b1); System.out.print( " + " ); printSimple(a2,b2); System.out.print( " = " ); printSimple(x,y); System.out.print( "\n" ); } private static void minus( int a1, int b1, int a2, int b2) { int x=a1*b2-a2*b1; int y=b1*b2; printSimple(a1,b1); System.out.print( " - " ); printSimple(a2,b2); System.out.print( " = " ); printSimple(x,y); System.out.print( "\n" ); } private static void multi( int a1, int b1, int a2, int b2) { int x=a1*a2; int y=b1*b2; printSimple(a1,b1); System.out.print( " * " ); printSimple(a2,b2); System.out.print( " = " ); printSimple(x,y); System.out.print( "\n" ); } private static void div( int a1, int b1, int a2, int b2) { int x=a1*b2; int y=b1*a2; if (y< 0 ){ x=(- 1 )*x; y=(- 1 )*y; } printSimple(a1,b1); System.out.print( " / " ); printSimple(a2,b2); System.out.print( " = " ); if (y== 0 ){ System.out.print( "Inf" ); } else { printSimple(x,y); } System.out.print( "\n" ); } private static void printSimple( int a, int b) { boolean isNegative= false ; if (a< 0 ){ isNegative= true ; a=a*(- 1 ); } int gcd=getGcd(a,b); a=a/gcd; b=b/gcd; int k=a/b; int x=a%b; int y=b; if (isNegative){ System.out.print( "(-" ); if (k== 0 ){ if (x!= 0 ) System.out.print(x+ "/" +y); else System.out.print( 0 ); } else { System.out.print(k); if (x!= 0 ) System.out.print( " " +x+ "/" +y); } System.out.print( ")" ); } else if (k== 0 ){ if (x!= 0 ){ System.out.print(x+ "/" +y); } else { System.out.print( 0 ); } } else { System.out.print(k); if (x!= 0 ){ System.out.print( " " +x+ "/" +y); } } } private static int getGcd( int x, int y) { if (y== 0 ) return x; else return getGcd(y,x%y); } } |