int func(int n){
if(n==1)
return 0;
else
return sqrt(n);
}
Where sqrt(n) is a C math.h library function.
I think that the running time entirely depends on the sqrt(n). However, I don't know how this function is actually implemented.
PS The general approach towards finding the square root of a number that I know of is using Newton's method. If I am not wrong, the time complexity using Newton's method turns out to be O(lg n). So should the answer be O(lg n)?
PPS Got this question in a recent test that I appeared for.
I am going to give a bit more general case answer, without assuming constant size of int
.
The answer is Theta(logn)
.
We know newton-raphson is Theta(logn) - that excludes Theta(n)
(assuming sqrt()
is as efficient as we can).
However, a general number n
requries log_2(n)
bits to encode - and you require to read all of it in order to get an accurate sqrt()
function. This excludes Theta(1)
and Theta(log(log(n))
.
From the above, we know that the complexity of the function is Theta(log(n))
.
As a side note, since O(log(n))
is a subset of O(n)
- it is also a valid answer, though not tight one. For more information about big Theta and big O and their differences, you might want to have a look on this thread .
This depends on the implementation of sqrt
and also on what kind of time complexity you are interested.
I would say you can consider it to be "constant", so O(1), in that sense: If you put in a random int
, it will in average take the same amount of time. (Reason: numbers with many digits are much more common).
But have a look here . Another possible answer is O(M(n)), where M(n) is the complexity of a multiplication and n is the number of digits in your integer.
This looking like a text-book question and a is perhaps meant to be a trap. The teacher perhaps wants to check if you can distinguish between computing sqrt
for a list of numbers (which would be O(n)), and a single number (which would be O(1)).
Be aware that the "correct" answer often also depends on the context in which it is asked.
Let n=2^m
Given T(n)=T(sqrt(n))+1
T(2^m)=T(2^m-1)+1
Let T(2^m)=S(m)
then,
S(m)=2S(m/2)+1
using master theorem -
S(m)=theta(m)
=theta(log(n))
Hence, time complexity is theta(log(n)) .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.