Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to do the sum of the n integers function that would have O(n^2)?

I want to write this simple function in a way that makes the big O notation of it O(n^2), how can I make that possible ?

int getSum(int n){ 
int sum = (n*(n+1))/2; 
return sum;

any ideas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’m not really sure why you want this, but you could do it with two nested loops:

int getSum(int n) {
    int sum = 0;
    for(int i = 1; i <= n; i++) {
        int x = 0;
        while(x++ < i) {
            sum++;
        }
    }
    return sum;
}

This runs 1+2+3+...+n times, which simplifies to (n^2+n)/2, hence O(n^2)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading