This is example 2 of Algorithm and Complexity Course in VNU - HCMUS
To running someSum.cpp and visualization.py you just do it
cd AlgorithmsAndComplexity/Ex02/src
bash someSum.sh
Compare your result with this image.
We are easy to predict complexity of someSum is n3 ( O(n3)). In first loop, we i variable is from 1 to n. Morever, j variable is from (n - i) to i2 . Therefore, someSum's number of operation is equal or less than n3 operations.
int SomeSum(int n, int& countAssign, int& countCompare){
int sum = 0, i = 1;
countAssign += 2;
int j;
while (++countCompare && i <= n){
j = n - i;
countAssign++;
while (++countCompare && j < i*i){
sum = sum + i*j;
countAssign++;
j = j+1;
countAssign++;
}
i = i + 1;
countAssign++;
}
return sum;
}
Common orders of growth.
Code | Notation | Code |
---|---|---|
Linear | for (int i = 0; i < n; ++i) { op(); for (int j = n-i; j < i*i; ++j) op(); } |
Function of number of opertions
Function of number of assign
Function of number of compare