可以明显代入找到通项公式 x = (s+n) / 2^(n+1) - 1
逐一用BigDecimal去计算,除数会出现无穷小数,所以要用整除方法,然后加1 即可,因为答案不能小于这个小数
而且答案是整数,所以+1
import java.util.*;
import java.math.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String str = sc.next();
BigDecimal s = new BigDecimal(str);
s = s.add(new BigDecimal(n));
BigDecimal devide = new BigDecimal(1);
while(n-- != -1){
devide = devide.multiply(new BigDecimal(2));
}
devide = devide.subtract(new BigDecimal(1));
s = s.divideToIntegralValue(devide).add(new BigDecimal(0.5)).setScale(0, BigDecimal.ROUND_HALF_UP);
System.out.println(s);
}
}
简短优化后
import java.util.*;
import java.math.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
BigDecimal s = new BigDecimal(sc.next()).add(new BigDecimal(n));
BigDecimal devide = new BigDecimal(1);
while(n-- != -1)
devide = devide.multiply(new BigDecimal(2));
System.out.println(s.divideToIntegralValue(devide.subtract(new BigDecimal(1))).add(new BigDecimal(1)));
}
}