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!
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.
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.
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.
There is no algorithm which would compute a square root in constant time.
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 double
s, 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With