J Fraction Comparision
签到题,比较两个分数的大小,但是交叉相乘会导致溢出。
那当然是依靠Java去解决啦。只是这个是真的太慢了,跑了差不多1700ms,还费了一大堆内存。
package acscut;
import java.math.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
BigInteger x=sc.nextBigInteger();
BigInteger a=sc.nextBigInteger();
BigInteger y=sc.nextBigInteger();
BigInteger b=sc.nextBigInteger();
BigInteger p1=x.multiply(b);
BigInteger p2=y.multiply(a);
if(p1.compareTo(p2)==0) {
System.out.println("=");
}
else if(p1.compareTo(p2)>0) {
System.out.println(">");
}
else {
System.out.println("<");
}
}
sc.close();
}
}
使用Long进行读入会稍微快一点。
package acscut;
import java.math.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
long tmp;
tmp=sc.nextLong();
BigInteger x=BigInteger.valueOf(tmp);
tmp=sc.nextLong();
BigInteger a=BigInteger.valueOf(tmp);
tmp=sc.nextLong();
BigInteger y=BigInteger.valueOf(tmp);
tmp=sc.nextLong();
BigInteger b=BigInteger.valueOf(tmp);
x=x.multiply(b);
y=y.multiply(a);
int res=x.compareTo(y);
if(res==0)
System.out.println("=");
else if(res>0)
System.out.println(">");
else
System.out.println("<");
}
sc.close();
}
}
从别人手里偷了一个快读,貌似BigInteger不能直接next,其他的功能都齐全了。
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
long tmp;
tmp=sc.nextLong();
BigInteger x=BigInteger.valueOf(tmp);
tmp=sc.nextLong();
BigInteger a=BigInteger.valueOf(tmp);
tmp=sc.nextLong();
BigInteger y=BigInteger.valueOf(tmp);
tmp=sc.nextLong();
BigInteger b=BigInteger.valueOf(tmp);
x=x.multiply(b);
y=y.multiply(a);
int res=x.compareTo(y);
if(res==0)
System.out.println("=");
else if(res>0)
System.out.println(">");
else
System.out.println("<");
}
}
}
class Scanner {
private BufferedReader br;
private StringTokenizer st;
Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
throw new IOError(e);
}
}
boolean hasNext() {
while (!st.hasMoreTokens()) {
String s = nextLine();
if (s == null) {
return false;
}
st = new StringTokenizer(s);
}
return true;
}
String next() {
hasNext();
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}