Algorithms | Analysis of Algorithms | Question 1

Last Updated :
Discuss
Comments

What is time complexity of fun()? 

C++
int fun(int n) {
    int count = 0;
    for (int i = n; i > 0; i /= 2)
        for (int j = 0; j < i; j++)
            count += 1;
    return count;
}
C
int fun(int n)
{
    int count = 0;
    for (int i = n; i > 0; i /= 2)
        for (int j = 0; j < i; j++)
            count += 1;
    return count;
}
Java
int fun(int n) {
    int count = 0;
    for (int i = n; i > 0; i /= 2)
        for (int j = 0; j < i; j++)
            count += 1;
    return count;
}
Python
def fun(n):
    count = 0
    i = n
    while i > 0:
        for j in range(i):
            count += 1
        i //= 2
    return count
C#
int Fun(int n) {
    int count = 0;
    for (int i = n; i > 0; i /= 2)
        for (int j = 0; j < i; j++)
            count += 1;
    return count;
}
JavaScript
function fun(n) {
    let count = 0;
    for (let i = n; i > 0; i = Math.floor(i / 2))
        for (let j = 0; j < i; j++)
            count += 1;
    return count;
}

O(n2)

O(n*log(n))

O(n)

O(n*log(n*Log(n)))

Share your thoughts in the comments