Time Complexity where loop variable is incremented by 1, 2, 3, 4 ..
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) {
i = i + j;
j++;
}
}
|
C
void fun( int n)
{
int j = 1, i = 0;
while (i < n)
{
i = i + j;
j++;
}
}
|
Java
static void fun( int n)
{
int j = 1 , i = 0 ;
while (i < n) {
i = i + j;
j++;
}
}
|
Python3
def fun(n):
j, i = 1 , 0
while i < n:
i = i + j
j + = 1
|
C#
using System;
static void fun( int n)
{
int j = 1, i = 0;
while (i < n) {
i = i + j;
j++;
}
}
|
Javascript
function fun(n) {
let j = 1,
i = 0;
while (i < n) {
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
Share your thoughts in the comments
Please Login to comment...