# Time Complexity of a Loop when Loop variable “Expands or Shrinks” exponentially

For such cases, time complexity of the loop is O(log(log(n))).The following cases analyse different aspects of the problem.

**Case 1 : **

`for` `(` `int` `i = 2; i <=n; i = ` `pow` `(i, k)) ` `{ ` ` ` `// some O(1) expressions or statements ` `} ` |

*chevron_right*

*filter_none*

In this case, i takes values 2, 2^{k}, (2^{k})^{k} = 2^{k2}, (2^{k2})^{k} = 2^{k3}, …, 2^{k}^{logk(log(n))}. The last term must be less than or equal to n, and we have 2^{k}^{logk(log(n))} = 2^{log(n)} = n, which completely agrees with the value of our last term. So there are in total log_{k}(log(n)) many iterations, and each iteration takes a constant amount of time to run, therefore the total time complexity is O(log(log(n))).

**Case 2 :**

`// func() is any constant root function ` `for` `(` `int` `i = n; i > 1; i = func(i)) ` `{ ` ` ` `// some O(1) expressions or statements ` `} ` |

*chevron_right*

*filter_none*

In this case, i takes values n, n^{1/k}, (n^{1/k})^{1/k} = n^{1/k2}, n^{1/k3}, …, n^{1/klogk(log(n))}, so there are in total log_{k}(log(n)) iterations and each iteration takes time O(1), so the total time complexity is O(log(log(n))).

Refer below article for analysis of different types of loops.

https://www.geeksforgeeks.org/analysis-of-algorithms-set-4-analysis-of-loops/

This article is contributed by **Rishav Raj**. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

## Recommended Posts:

- Time Complexity where loop variable is incremented by 1, 2, 3, 4 ..
- Time Complexity of Loop with Powers
- Time taken by Loop unrolling vs Normal loop
- Loop Invariant Condition with Examples of Sorting Algorithms
- A Time Complexity Question
- Time Complexity of building a heap
- An interesting time complexity question
- Practice Questions on Time Complexity Analysis
- Time complexity of recursive Fibonacci program
- Understanding Time Complexity with Simple Examples
- Time Complexity Analysis | Tower Of Hanoi (Recursion)
- Python Code for time Complexity plot of Heap Sort
- Cyclomatic Complexity
- What does 'Space Complexity' mean?
- Knowing the complexity in competitive programming