A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/dsa/time-complexity-loop-loop-variable-expands-shrinks-exponentially/ below:

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

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

Last Updated : 08 May, 2019

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

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

In this case, i takes values 2, 2

k

, (2

k

)

k

= 2

k2

, (2

k2

)

k

= 2

k3

, ..., 2

klogk(log(n))

. The last term must be less than or equal to n, and we have 2

klogk(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 : CPP
// 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, 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/dsa/how-to-analyse-loops-for-complexity-analysis-of-algorithms/

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4