-6

How many simple operations are performed in a simple java loop?

int result = 0;
for (int i = 0; i <= n; i++) {
    result = result + i;
}

We discussed in class and agreed on somewhat 8n+13 simple operations, but it would be nice with a correct, documented result. Thanks.

cascho
  • 1
  • 1

4 Answers4

2

It's O(n). All other fancy 8n +13 can be just reduced to regular O(n)

Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63
1

It will be O(n)

O(n): Time Complexity of a loop is considered as O(n) if the loop variables is incremented / decremented by a constant amount. For example following functions have O(n) time complexity.

Example

 // Here c is a positive integer constant   
   for (int i = 1; i <= n; i += c) {  
        // some O(1) expressions
   }

   for (int i = n; i > 0; i -= c) {
        // some O(1) expressions
   }

In your case i and result is incrementing by constant rate .

Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

I think you ask about the complexity in terms of number of operations (not the order of magnitude) so I think first is to divide it to small operations and then make the calculation:

int result = 0; // 1 op
int i = 0; // 1op
while (i <= n) { // n op of comparison
    result + i; // n op (1 op * n because is inside the loop)
    result = [result of operation]; // n op 
    i + 1 // n op
    i = [result of operation]; // n op
}

So you have 5n+2 operations that is O(n) magnitude. Get in mind (as you can see in other questions) that the important thing is normally to get only the order of magnitude.

Also you can have the while divided more in a compassion and a jump. And assignments and declarations can been split.

PhoneixS
  • 10,574
  • 6
  • 57
  • 73
-1

Its O(n) . Performance is measured in terms of Big oh O . O(0) is better performing than O(1). O(n) means which consumes more time and hence require more processing time, where n is the number of iterations.

Alexis King
  • 43,109
  • 15
  • 131
  • 205
SabaRish
  • 105
  • 11