I need to find a closest upper and lower bound of following code. I am beeginer in this so sorry for my mistake.
Upper bound for p() is O(log(n)), and lower bound is O(1)
Upper bound for notp() is O(log(n)), and lower bound is O(1)
I think that lower bound is O(1) because if I have n=4 then I get in the loop and since n%i==0 I call p() and it notice that is not a prime number so O(1) then since i=2 the other notp would not be executed. That is bast case scenario.
Worst case scenario that I go through loop so that log(n), and execute a p and a upper bound is O(log(n)) so it is O(log(n)^2) but I am not so sure that this is good, please tell me where I made a mistake?
int i;
for (i = 2; i*i <= n; i++) {
if (n % i == 0) {
p();
break;
}
}
if(i*i > n)
notp();
For order calculations, you would normally multiply them together when there is a loop.
That would be O(n), as the loop is a single case.
A nested loop would be
That becomes O( n^2 ) as they are additive.
If you have non-nested loops...
Then the O( x ), is the largest term. That is because for very large n, the smaller values of x don't matter.
So you have a loop in your case, which is O( sqrt( n ) ). That is because it is limited by i *i being less than n.
Then either one of p() or notp() will be called.
(I think p() and notp() are the wrong way round).
Re-factoring your code....
So we have the O( sqrt(n) ) time plus either of the p / notp functions which are O( log(n) )
O( sqrt(n ) + log(n) )
As the sqrt grows faster than n, it overpowers the log(n) wikipedia Big O, leaving it as the final value.
O( sqrt(n) )
As the termination condition of the loop is
i*i <= n
, the most possible number of iteration of the loop issqrt(n)
. As there is abreak
in the condition ofn % i == 0
, the worst case of this part issqrt(n) + log(n)
which isO(sqrt(n))
. Also, eighter the second condition is true or not, as the worst case ofnopt()
isO(log(n))
, the worst case of the algorithm in total isO(sqrt(n))
.