标签:class 笔试题 ati 溢出 next 试题 math java sys
二分查找
\(x+x^2=x(x+1)=h\) 二分查找求解。
x下界为0, 上界不好找(如果设为h, java中long类型溢出)。我们转化问题为查找x+1,下界为1, 上界为 \(\lceil \sqrt{h} \rceil\) 。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long h = sc.nextLong();
long l = 1L, r = (long)Math.sqrt(h) + 1L;
while(l < r) {
long mid = (l+r+1) / 2;
if(mid*(mid-1) <= h)
l = mid;
else
r = mid-1;
}
System.out.println(l-1);
}
}
标签:class 笔试题 ati 溢出 next 试题 math java sys
原文地址:https://www.cnblogs.com/lixyuan/p/13143836.html