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?
>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)