Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Worst case time complexity of Math.sqrt in java

We have a test exercise where you need to find out whether a given N number is a square of another number or no, with the smallest time complexity.

I wrote:

public static boolean what2(int n) {
    double newN = (double)n;
    double x = Math.sqrt(newN);
    int y = (int)x;
    if (y * y == n)
        return false;
    else
        return true;
}

I looked online and specifically on SO to try and find the complexity of sqrt but couldn't find it. This SO post is for C# and says its O(1), and this Java post says its O(1) but could potentially iterate over all doubles.

I'm trying to understand the worst time complexity of this method. All other operations are O(1) so this is the only factor. Would appreciate any feedback!

like image 782
roony Avatar asked Feb 20 '16 13:02

roony


People also ask

What is time complexity of sqrt Java?

Looking at the actual code, which is not used by Oracle's java anyway, the complexity of Math. sqrt is O(1). It loops 52 times: that's not Log(N), that's constant time, much less efficient than using the floating point opcode, but still constant time.

What is the time complexity of sqrt?

The best case time complexity to find the square root is O(log(n)), where n is the input number. In C++, we can use the pow function of the math. h library or the sqrt function of the cmath library to find the square root of a number.

What is Big O of square root N?

As a result its time complexity is O(sqrt(n)) = O(sqrt(2^s)) = O(2^(s/2)) , where s is the size of the input, which is exponential.

Is sqrt constant time?

There is no algorithm which would compute a square root in constant time.


1 Answers

Using the floating point conversion is OK because java's int type is 32 bits and java's double type is the IEEE 64 bit format that can represent all values of 32 bit integers exactly.

If you were to implement your function for long, you would need to be more careful because many large long values are not represented exactly as doubles, so taking the square root and converting it to an integer type might not yield the actual square root.

All operations in your implementation execute in constant time, so the complexity of your solution is indeed O(1).

like image 84
chqrlie Avatar answered Sep 17 '22 15:09

chqrlie