Open In App
Related Articles

Time Complexity where loop variable is incremented by 1, 2, 3, 4 ..

Improve Article
Improve
Save Article
Save
Like Article
Like

What is the time complexity of below code? 

C++




#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




void fun(int n)
{
   int j = 1, i = 0;
   while (i < n)
   {
       // Some O(1) task
       i = i + j;
       j++;
   }
}


Java




// Method with a parameter 'n'
static void fun(int n)
{
    // Initializing variables
    int j = 1, i = 0;
 
    // While loop with condition
    while (i < n) {
        // Some O(1) task
        i = i + j;
        j++;
    }
}


Python3




def fun(n):
    j, i = 1, 0
    while i < n:
        # Some O(1) task
        i = i + j
        j += 1


C#




using System;
 
static void fun(int n)
{
    int j = 1, i = 0;
    while (i < n) {
        // Some O(1) task
        i = i + j;
        j++;
    }
}


Javascript




function fun(n) {
    let j = 1,
        i = 0;
    while (i < n) {
        // Some O(1) task
        i = i + j;
        j++;
    }
}


The loop variable ‘i’ is incremented by 1, 2, 3, 4, … until i becomes greater than or equal to n. The value of i is x(x+1)/2 after x iterations. So if loop runs x times, then x(x+1)/2 < n. Therefore time complexity can be written as ?(?n). 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above


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!

Last Updated : 30 Nov, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials