【大数问题】 FZU 2036 Log Calculator

用java保证精度。。。当x>=32时,在精度范围内log2(2x+1)=x。否则将a-b转化为double类型直接计算。

import java.util.Scanner;
import java.math.BigInteger;
import java.math.BigDecimal;
import java.math.*;

public class Main
{
	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		BigDecimal a, b, ans, c;
		c = BigDecimal.valueOf(32);
		int t = scanner.nextInt();
		for(int i = 1; i <= t; i++) {
			a = scanner.nextBigDecimal();
			b = scanner.nextBigDecimal();
			if(a.compareTo(b) <= 0) {
				ans = a;
				a = b;
				b = ans;
			}
			a = a.subtract(b);
			if(a.compareTo(c) >= 0) ans = a.add(b);
			else {
				double tmp = Math.pow(2, a.doubleValue()) + 1;
				tmp = Math.log(tmp)/Math.log((double)2);
				ans = b.add(BigDecimal.valueOf(tmp));
			}
			ans = ans.setScale(9, BigDecimal.ROUND_HALF_UP);
			System.out.println("Case " + i + ": " + ans.toPlainString());
		}
	}
}


你可能感兴趣的:(FZU)