
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
An interesting time complexity question in C++
Time complexity can be defined as the time required by the algorithm to run its average case.
Let's see and calculate the time complexity of some of the basic functions.
Method
void counter(int n){ for(int i = 0 ; i < n ; i++){ for(int j = 1 ; j<n ; j += i ){ cout<<i<<” ”<<j; } cout<<endl; } }
The above method will run n/I times for all values of i. i.e. n times for the first iteration and 1 time for the last iteration.
According to this, the total time complexity is
(n/1 + n/2 + n/3 + …. + n/n) = n (1/1 + ½ + ⅓ + …. 1/n)
Now the value of (1/1 + ½ + ⅓ + …. 1/n) is equal to O(log n).
The time complexity of this code is O(nlogn).
Method
void counter(n){ int i , j ; for(int i = 1 ; i <= n ; i++){ for(j = 1; j <= log(i) ; j++){ cout<<i<<” ”<<j; } } }
The total complexity of the function is O(log 1) + O(log 2) + O(log 3) + …. + O(log n) which is O(log n!).
- Related Articles
- An Insertion Sort time complexity question in C++
- Amortized time complexity in Data Structures
- Time and Space Complexity in Data Structure
- Practice Questions on Time Complexity Analysis in C++
- Time and Space Complexity Analysis of Queue operations
- Check for balanced parentheses in an expression O(1) space O(N^2) time complexity in Python
- Check for balanced parentheses in an expression - O(1) space - O(N^2) time complexity in C++
- Asymptotic Complexity
- Amortized Complexity
- How to find the complexity of an Image instance using FabricJS?
- Printing Interesting pattern in C++
- An interesting method to print reverse of a linked list in C++
- Question
- What is 'Space Complexity’?
- Complexity of Interval Heap Operations

Advertisements