I need help with finding out the time complexity of the first and second loop(the nested for-while loop), I'm not so sure of my answers:
for the first loop: O(log n)
for the second loop: O(sqrt(n) logn)
The Code:
public static int findLength(int n){
int length = 0;
//FIRST LOOP
while (n%2==0){
length++;
n /= 2;
}
//SECOND LOOP
for (int i = 3; i <= Math.sqrt(n); i+= 2) {
while (n%i == 0) {
length++;
n /= i;
}
}
if (n > 2)
length++;
return length;
}
FIRST LOOP
n
is odd
O(1)
n
is power of 2
n
)O(log n)
Overall time complexity: O(log n)
SECOND LOOP
First Extreme: n
is prime
while
loop doesn't run at allO(sqrt(n))
Second Extreme: n = (p1 ^ q1) * (p2 ^ q2) * .. * (pn ^ qn)
, where p1, p2 .. pn
are primes (generalization of first extreme)
q1 + q2 + ... + qn
O(log n)
Overall time complexity: O(sqrt(n))