The Wayback Machine - https://web.archive.org/web/20240118165932/https://www.geeksforgeeks.org/time-complexity-loop-loop-variable-expands-shrinks-exponentially/
Open In App
Related Articles

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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
}


In this case, i takes values 2, 2k, (2k)k = 2k2, (2k2)k = 2k3, …, 2klogk(log(n)). The last term must be less than or equal to n, and we have 2klogk(log(n)) = 2log(n) = n, which completely agrees with the value of our last term. So there are in total logk(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
}


In this case, i takes values n, n1/k, (n1/k)1/k = n1/k2, n1/k3, …, n1/klogk(log(n)), so there are in total logk(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/

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 08 May, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials