c loop function computing time complexity

Viewed 43

I am learning to compute the time complexity of algorithms. Simple loops and nested loops can be compute but how can I compute if there are assignments inside the loop. For example :

void f(int n){
    int count=0;
    for(int i=2;i<=n;i++){
        if(i%2==0){
            count++;
        }
        else{
            i=(i-1)*i;
        }
    }
}

i = (i-1)*i affects how many times the loop will run. How can I compute the time complexity of this function?

2 Answers

As i * (i-1) is even all the time ((i * (i-1)) % 2 == 0), if the else part will be true for one time in the loop, i++ makes the i odd number. As result, after the first odd i in the loop, always the condition goes inside the else part.

Therefore, as after the first iteration, i will be equal to 3 which is odd and goes inside the else part, i will be increased by i * (i-1) +‌ 1 in each iteration. Hence, if we denote the time complexity of the loop by T(n), we can write asymptotically: T(n) = T(\sqrt(n)) + 1. So, if n = 2^{2^k}, T(n) = k = log(log(n)).

There is no general rule to calculate the time complexity for such algorithms. You have to use your knowledge of mathematics to get the complexity.

For this particular algorithm, I would approach it like this.

Since initially i=2 and it is even, let's ignore that first iteration. So I am only considering from i=3. From there I will always be odd.

Your expression i = (i-1)*i along with the i++ in the for loop finally evaluates to i = (i-1)*i+1

If you consider i=3 as 1st iteration and i(j) is the value of i in the jth iteration, then i(1)=3. Also

i(j) = [i(j-1)]^2 - i(j-1) + 1

The above equation is called a recurrence relation and there are standard mathematical ways to solve it and get the value of i as a function of j. Sometimes it is possible to get and sometimes it might be very difficult or impossible. Frankly, I don't know how to solve this one.

But generally, we don't get situations where you need to go that far. In practical situations, I would just assume that the complexity is logarithmic because the value of i is increasing exponentially.

Related