Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the complexity of this sum algorithm?

Tags:

c

algorithm

#include <stdio.h>

int main() {
    int N = 8;  /* for example */
    int sum = 0;
    for (int i = 1; i <= N; i++)
        for (int j = 1; j <= i*i; j++)
            sum++;

    printf("Sum = %d\n", sum);
    return 0;
}

for each n value (i variable), j values will be n^2. So the complexity will be n . n^2 = n^3. Is that correct?

If problem becomes:

#include <stdio.h>

int main() {
    int N = 8;  /* for example */
    int sum = 0;
    for (int i = 1; i <= N; i++)
        for (int j = 1; j <= i*i; j++)
            for (int k = 1; k <= j*j; k++)
                sum++;

    printf("Sum = %d\n", sum);
    return 0;
}

Then you use existing n^3 . n^2 = n^5 ? Is that correct?

like image 380
Angus Comber Avatar asked Feb 01 '14 14:02

Angus Comber


People also ask

What is the complexity of sum?

The time complexity of the sum() function is linear in the number of elements in the iterable (list, tuple, set, etc.). The reason is that you need to go over all elements in the iterable and add them to a sum variable. Thus, you need to “touch” every iterable element once.

How do you calculate complexity of an algorithm?

If your algorithm runs in a time proportional to the logarithm of the input data size, that is log ⁡ ( n ) \log(n) log(n), then you have O ( log ⁡ ( n ) ) \mathcal{O}(\log(n)) O(log(n)) complexity. This type of complexity is usually present in algorithms that somehow divide the input size.

What is the complexity of the summation of n number?

The running time of summing, one after the other, the first n consecutive numbers is indeed O(n). But the complexity of the result, that is the size of “sum from 1 to n” = n(n – 1) / 2 is O(n ^ 2).

What is the complexity formula?

The time complexity, measured in the number of comparisons, then becomes T(n) = n - 1. In general, an elementary operation must have two properties: There can't be any other operations that are performed more frequently as the size of the input grows.


1 Answers

We have i and j < i*i and k < j*j which is x^1 * x^2 * (x^2)^2 = x^3 * x^4 = x^7 by my count.

In particular, since 1 < i < N we have O(N) for the i loop. Since 1 < j <= i^2 <= N^2 we have O(n^2) for the second loop. Extending the logic, we have 1 < k <= j^2 <= (i^2)^2 <= N^4 for the third loop.

Inner to Outer loops, we execute up to N^4 times for each j loop, and up to N^2 times for each i loop, and up to N times over the i loop, making the total be of order N^4 * N^2 * N = N^7 = O(N^7).

like image 166
abiessu Avatar answered Oct 18 '22 17:10

abiessu