Open In App
Related Articles

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

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

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). 



Last Updated : 30 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads