2199 Can you solve this equation?

Problem Description

Now,given the equation 8x^4 + 7x^3 + 2x^2 + 3x + 6 == Y,can you find its solution between 0 and 100;
Now please try your lucky.

Input

The first line of the input contains an integer T(1<=T<=100) which means the number of test cases. Then T lines follow, each line has a real number Y (fabs(Y) <= 1e10);

Output

For each test case, you should just output one real number(accurate up to 4 decimal places),which is the solution of the equation,or “No solution!”,if there is no solution for the equation between 0 and 100.

Sample Input

1
2
3
2
100
-4

Sample Output

1
2
1.6152
No solution!

Suggest Answer

一开始是想着用暴力做的,因为x的范围是0-100,用暴力做得不到正确答案,因为答案出来都是浮点数,暴力枚举的都是整数.看看题目的函数8x^4 + 7x^3 + 2x^2 + 3x + 6 == Y,是一个单调递增的函数,所以可以用二分来做.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.*;

public class _2199 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int T = input.nextInt();
for (int i = 0; i < T; i++) {
double Y = input.nextDouble();
if (calc(0) <= Y && Y <= calc(100)) {
double left = 0, right = 100;
while (right - left > 1e-10) {
double middle = (left + right) / 2;
if (calc(middle) > Y) {
right = middle - 1e-10;
} else {
left = middle + 1e-10;
}
}
System.out.println(String.format("%.4f", (left + right) / 2));
} else {
System.out.println("No solution!");
}
}
input.close();
}

private static double calc(double x) {
return 8 * x * x * x * x + 7 * x * x * x + 2 * x * x + 3 * x + 6;
}
}