Search code examples
algorithmtime-complexitybig-oanalysismodulo

Time complexity for while loops using modulo


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;
    }

Solution

  • FIRST LOOP

    • First Extreme: n is odd
      • loop doesn't run
      • Time: O(1)
    • Second Extreme: n is power of 2
      • loop runs maximum no of times (with respect to different values of n)
      • Time: O(log n)

    Overall time complexity: O(log n)


    SECOND LOOP

    • First Extreme: n is prime

      • Nested while loop doesn't run at all
      • Time: O(sqrt(n))
    • Second Extreme: n = (p1 ^ q1) * (p2 ^ q2) * .. * (pn ^ qn), where p1, p2 .. pn are primes (generalization of first extreme)

      • Total number of operations (excluding loop counters / test expressions): q1 + q2 + ... + qn
      • Time: O(log n)

    Overall time complexity: O(sqrt(n))