国内做题,从来没有用过JAVA。介于北美题对时间卡得没那么紧,而java对大数的操作比较方便,所以练习了一下。
题目的意思是,给定exp和bigNum,问是否存在answer,answer的exp次方是bigNum。其中bigNum的范围是1到10^100。
有了java的BigInteger,用二分搜索做这题很舒服。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Scanner;
public class Pro3 {
/**
* @param args
*/
public static Scanner in=null;
public static PrintWriter out=null;
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
in = new Scanner (new File("D:\\ACM_UNL\\region2009\\pkg\\InputData\\in3.txt"));
out = new PrintWriter (new File("D:\\ACM_UNL\\region2009\\pkg\\MyOutput\\out3.txt"));
for(int i=1;;i++)
{
int exp=in.nextInt();
if(exp==0) break;
BigInteger bigNum=in.nextBigInteger();
out.println("Case "+i+": "+Process(exp,bigNum));
out.println();
}
in.close();
out.close();
}
public static String Process(int exp, BigInteger bigNum)
{
BigInteger low=BigInteger.ONE;
BigInteger high=bigNum;
BigInteger answer=null;
while(low.compareTo(high)<=0)
{
answer=low.add(high).divide(new BigInteger("2"));
BigInteger test=answer.pow(exp);
if(bigNum.compareTo(test)==0) return answer.toString();
else if(bigNum.compareTo(test)<0) high=answer.subtract(BigInteger.ONE);
else low=answer.add(BigInteger.ONE);
}
return "No solution";
}
}