B - Can you solve this equation?

Description
现在,给出等式8* X^4+ 7* X^3+ 2* X^2+ 3 * X +6= Y,请找出他在0和100之间的解(包含0和100)。
现在,请你试试运气。。。。

Input

输入的第一行包含一个整数T(1 <= T <=100),表示测试用例的数目。接下来T个数字,每一行都有一个实数Y(abs(Y)<=10^10);

Output
对于每个测试用例,如果有解,你应该输出一个实数(精确到小数点后4位,四舍五入),如果在0到100之间无解,就输出“No solution!”。

Sample Input

2

100

-4

Sample Output

1.6152

No solution!

题目很简单,直接用二分搜索法查找满足条件的x,排除y值可以取的范围,同时要注意结果的精度,四舍五入。
代码如下:

#include <iostream>
#include <iomanip>
#include <math.h>
#include <algorithm>
using namespace std;

const double EPS = 1e-7;

int f(double x, double y)
{
    if(8 * pow(x,4) + 7 * pow(x,3) + 2 * pow(x,2) + 3 * x + 6 < y)
        return 1;
    return 0;
}

double bs(double y)
{
    double lo = 0, hi = 100;
    double mi, ans=hi+1;
    while(lo + EPS  < hi)
    {
        mi = (lo + hi) / 2.0;
        if(f(mi,y))
        {
            lo = mi;
            if(ans == hi + 1)
                ans = mi;
            ans = max(ans,mi);
        }
        else
        {
            hi = mi;
            ans = min(ans,mi);
        }
    }
    if(ans == hi + 1)
        ans = -1;
    return ans;
}

int main()
{
    int t;
    double y;
    const long long max_num = 8 * pow(100,4) + 7 * pow(100,3) + 2 * pow(100,2) + 3 * 100 + 6;
    cin >> t;
    while(t--)
    {
        cin >> y;
        if(y > max_num || y < 6)
        {
            cout << "No solution!" << endl;
        }
        else
        {
            if(y == 6)
            {
                cout << fixed << setprecision(4) << 0.0000 << endl;
                continue;
            }
            if(y == max_num)
            {
                cout << fixed << setprecision(4) << 100.0000 << endl;
                continue;
            }
            double ans = bs(y);
            if(ans != -1)
                cout << fixed << setprecision(4) << (int)(ans * 10000 + 0.5) / 10000.0 << endl;
            else
                cout << "No solution!" << endl;
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值