Square root#3968

Square root (Editorial)

Algorithm Analysis

Consider the function f(x) = x^2 + \sqrt{x}. It is obvious that:

Thus, the root of the equation

f(x) = C

lies in the interval . The function is strictly increasing. We search for the root using binary search.

Example

Consider the graph of the function f(x) = x^2 + \sqrt{x}. It can be noticed that:

Therefore, the root of the equation f(x) = C lies in the interval [0; \sqrt{C}] and can be found by binary search.

Function graph

Algorithm Implementation

Declare the constant EPS and the function f(x).

#define EPS 1e-10

double f(double x)
{
    return x * x + sqrt(x);
}

The main part of the program. Read the value of .

scanf("%lf", &c);

Set the binary search bounds [left; right] = [0; C].

left = 0; right = c;

Start the binary search.

while (right - left > EPS)
{
    middle = (left + right) / 2;
    y = f(middle);
    if (y > c) right = middle; else left = middle;
}

Output the answer.

printf("%lf\n", left);

Java Implementation

import java.util.*;

public class Main
{
    static double f(double x)
    {
        return x * x + Math.sqrt(x);
    }

    public static void main(String[] args)
    {
        Scanner con = new Scanner(System.in);
        double c = con.nextDouble();
        double left = 0, right = c;

        while (right - left > 1e-10)
        {
            double middle = (left + right) / 2;
            double y = f(middle);
            if (y > c) right = middle; else left = middle;
        }
        System.out.println(left);
        con.close();
    }
}