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

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

Last Updated : 08 May, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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/



Similar Reads

Time Complexity where loop variable is incremented by 1, 2, 3, 4 ..
What is the time complexity of below code? C/C++ Code #include <iostream> using namespace std; void fun(int n) { int j = 1, i = 0; while (i < n) { // Some O(1) task i = i + j; j++; } } C/C++ Code void fun(int n) { int j = 1, i = 0; while (i < n) { // Some O(1) task i = i + j; j++; } } Java Code // Method with a parameter 'n' static void
2 min read
Time Complexity and Space Complexity
Generally, there is always more than one way to solve a problem in computer science with different algorithms. Therefore, it is highly required to use a method to compare the solutions in order to judge which one is more optimal. The method must be: Independent of the machine and its configuration, on which the algorithm is running on.Shows a direc
14 min read
Time Complexity of Loop with Powers
What is the time complexity of the below function? [GFGTABS] C++ void fun(int n, int k) { for (int i = 1; i <= n; i++) { int p = pow(i, k); for (int j = 1; j <= p; j++) { // Some O(1) work } } } // This code is contributed by Shubham Singh C void fun(int n, int k) { for (int i = 1; i <= n; i++) { int p = pow(i, k); for (int j = 1; j <=
2 min read
Time taken by Loop unrolling vs Normal loop
We have discussed loop unrolling. The idea is to increase performance by grouping loop statements so that there are less number of loop control instruction and loop test instructions C/C++ Code // CPP program to compare normal loops and // loops with unrolling technique #include <iostream> #include <time.h> using namespace std; int main
6 min read
Difference between Instance Variable and Class Variable
Instance Variable: It is basically a class variable without a static modifier and is usually shared by all class instances. Across different objects, these variables can have different values. They are tied to a particular object instance of the class, therefore, the contents of an instance variable are totally independent of one object instance to
2 min read
Comparison of an Array and Hash table in terms of Storage structure and Access time complexity
Arrays and Hash Tables are two of the most widely used data structures in computer science, both serving as efficient solutions for storing and accessing data in Java. They have different storage structures and time complexities, making them suitable for different use cases. In this article, we will explore the differences between arrays and hash t
3 min read
Time Complexity Analysis | Tower Of Hanoi (Recursion)
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk ca
2 min read
Queries of nCr%p in O(1) time complexity
Given Q queries and P where P is a prime number, each query has two numbers N and R and the task is to calculate nCr mod p. Constraints: N <= 106 R <= 106 p is a prime number Examples: Input: Q = 2 p = 1000000007 1st query: N = 15, R = 4 2nd query: N = 20, R = 3 Output: 1st query: 1365 2nd query: 1140 15!/(4!*(15-4)!)%1000000007 = 1365 20!/(2
9 min read
Python Code for time Complexity plot of Heap Sort
Prerequisite : HeapSort Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. We implement Heap Sort here, call it for different sized random lists, meas
3 min read
How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
Pre-requisite: Sieve of Eratosthenes What is Sieve of Eratosthenes algorithm? In order to analyze it, let's take a number n and the task is to print the prime numbers less than n. Therefore, by definition of Sieve of Eratosthenes, for every prime number, it has to check the multiples of the prime and mark it as composite. This process continues unt
3 min read
Time Complexity of Euclidean Algorithm
In this article, we will discuss the time complexity of the Euclidean Algorithm which is O(log(min(a, b)) and it is achieved. Euclid's Algorithm: It is an efficient method for finding the GCD(Greatest Common Divisor) of two integers. The time complexity of this algorithm is O(log(min(a, b)). Recursively it can be expressed as: gcd(a, b) = gcd(b, a%
4 min read
Miscellaneous Problems of Time Complexity
Prerequisite : Asymptotic Notations Time Complexity :Time complexity is the time needed by an algorithm expressed as a function of the size of a problem. It can also be defined as the amount of computer time it needs to run a program to completion. When we solve a problem of time complexity then this definition help the most - "It is the number of
15+ min read
Logarithmic vs Double Logarithmic Time Complexity
Time complexity is the computational complexity that describes the amount of time it takes to run an algorithm.” Now, we know that there can be multiple ways we can solve any particular problem. But, knowing how we can solve the problem in the most efficient way is important in real-life applications. To find the efficiency of any algorithm or prob
3 min read
Can Run Time Complexity of a comparison-based sorting algorithm be less than N logN?
Sorting algorithms are the means to sort a given set of data in an order according to the requirement of the user. They are primarily used to sort data in an increasing or decreasing manner. There are two types of sorting algorithms: Comparison-based sorting algorithmsNon-comparison-based sorting algorithms Comparison-based sorting algorithms: The
3 min read
Step Count Method for Time Complexity Analysis
What is Time Complexity? Time Complexity is the amount of time taken by the algorithm to run. It measures the time taken to execute each statement of code in an algorithm. Time Complexity can be calculated by using Two types of methods. They are: Step Count MethodAsymptotic Notation. Here, we will discuss the Step Count Method. What is Step Count M
4 min read
Time and Space complexity analysis of Selection Sort
The Selection sort algorithm has a time complexity of O(n^2) and a space complexity of O(1) since it does not require any additional memory space apart from a temporary variable used for swapping. Time Complexity Analysis of Selection Sort:Best-case: O(n2), best case occurs when the array is already sorted. (where n is the number of integers in an
2 min read
Time and Space Complexity Analysis of Tree Traversal Algorithms
Let us discuss the Time and Space complexity of different Tree Traversal techniques, such as Inorder Traversal, Preorder Traversal, Postorder Traversal, etc. Time Complexity of Tree Traversal AlgorithmsLet us see different corner cases: Complexity function T(n) — for all problems where tree traversal is involved — can be defined as: T(n) = T(k) + T
2 min read
Time and Space Complexity analysis of Stack operations
What is Stack?Stack is a linear data structure that follows a particular order in which the elements are inserted and deleted. A stack follows the principle of last in first out(LIFO) which means that the last element inserted into the stack should be removed first. Consider an example of plates stacked over one another in the canteen. The plate wh
15+ min read
Time and Space complexity of 1-D and 2-D Array Operations
The time and space complexity of one-dimensional and two-dimensional array operations can vary depending on the specific operation. Here, we'll discuss common array operations and provide insights into their time and space complexities for one-dimensional and two-dimensional arrays. One-Dimensional Array Operations: Accessing an Element by Index:Ti
3 min read
Time Complexity of building a heap
Consider the following algorithm for building a Heap of an input array A. BUILD-HEAP(A) heapsize := size(A); for i := floor(heapsize/2) downto 1 do HEAPIFY(A, i); end for END A quick look over the above algorithm suggests that the running time is [Tex]O(n * lg(n)) [/Tex] since each call to Heapify costs [Tex]O(lg(n)) [/Tex]and Build-Heap makes [Tex
2 min read
Time complexity of insertion sort when there are O(n) inversions?
What is an inversion? Given an array arr[], a pair arr[i] and arr[j] forms an inversion if arr[i] j. For example, the array {1, 3, 2, 5} has one inversion (3, 2) and array {5, 4, 3} has inversions (5, 4), (5, 3) and (4, 3). We have discussed a merge sort based algorithm to count inversions What is the time complexity of Insertion Sort when there ar
1 min read
Can QuickSort be implemented in O(nLogn) worst case time complexity?
The worst-case time complexity of a typical implementation of QuickSort is O(n2). The worst case occurs when the picked pivot is always an extreme (smallest or largest) element. This happens when the input array is sorted or reverses sorted and either the first or last element is picked as a pivot. Although randomized QuickSort works well even when
15+ min read
An interesting time complexity question
What is the time complexity of following function fun()? int fun(int n) { for (int i = 1; i <= n; i++) { for (int j = 1; j < n; j += i) { // Some O(1) task } } } For i = 1, the inner loop is executed n times. For i = 2, the inner loop is executed approximately n/2 times. For i = 3, the inner loop is executed approximately n/3 times. For i = 4
2 min read
Sieve of Eratosthenes in 0(n) time complexity
The classical Sieve of Eratosthenes algorithm takes O(N log (log N)) time to find all prime numbers less than N. In this article, a modified Sieve is discussed that works in O(N) time.Example : Given a number N, print all prime numbers smaller than N Input : int N = 15 Output : 2 3 5 7 11 13 Input : int N = 20 Output : 2 3 5 7 11 13 17 19 Manipulat
12 min read
An Insertion Sort time complexity question
Question : How much time Insertion sort takes to sort an array of size n in below form? arr[] = 2, 1, 4, 3, 6, 5,....i, i-1, .....n, n-1 Answer : At first look, it seems like Insertion Sort would take O(n2) time, but it actually takes O(n) time How? Let us take a closer look at below code. /* Function to sort an array using insertion sort*/ void in
2 min read
What does Constant Time Complexity or Big O(1) mean?
Big O notation is a concept, in computer science and mathematics that allows us to analyse and describe the efficiency of algorithms for worst cases. It provides a way to measure how the runtime of an algorithm or function changes as the input size grows. In this article we'll explore the idea of O(1) complexity, what it signifies and provide examp
5 min read
Time and Space Complexity Analysis of Queue operations
What is Queue?Queue is a linear data structure that follows FIFO approach (First In First Out). One can imagine a queue as a line of people waiting in sequential order which starts from the beginning of the line. It is an ordered list in which insertions are done at one end which is known as the rear and deletions are done from the other end known
15+ min read
Time and Space Complexity of Insertion Sort
What is Insertion Sort?Insertion sort is a simple sorting algorithm that works similarly to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed in the correct position in the sorted part. To sort an array of size N in ascending order itera
2 min read
Time and Space Complexity of Breadth First Search (BFS)
What is Breadth First Search?The Breadth First Search (BFS) algorithm is used to search a graph data structure for a node that meets a set of criteria. It starts at the root of the graph and visits all nodes at the current depth level before moving on to the nodes at the next depth level. Although there are other methods for traversing the graph, B
3 min read
Time and Space Complexity of Floyd Warshall Algorithm
The Floyd Warshall Algorithm has a time complexity of O(V3) and a space complexity of O(V2), where V represents the number of vertices in the graph. This algorithm computes the shortest paths between all pairs of vertices in a weighted graph. The time complexity arises from the triple nested loops used to update the shortest path matrix, while the
3 min read
Practice Tags :
three90RightbarBannerImg