0
public class foo{   
    public static void main(String[] args){
         int a = 1;
         int b = 1;
         int n = 4;

         //Focus is on the below for-loop
         for(int x=1;x<=n;x++){           
             c=a+b;
         }
    }
}
  • x=1 --> O(1) //One assignment statement
  • x<=n --> O(n+1) //checks n times and then a following time
  • x++ --> O(n) //increments n times
  • c=a+b --> O(4n) //increments n times, but the statement itself has four operations, LOAD A + LOAD B + ADD + STORE C

Now how would I combine these? i.e. Do I add, or multiply, and why? Thanks in advance.

Gray
  • 115,027
  • 24
  • 293
  • 354
Ari K
  • 434
  • 2
  • 18

2 Answers2

0

Your thinking is valid, but that is not BigOh To calculate BigOh you need Asymptotic analysis

There is an awesome answer by a university professor here, you should check out the last part of his answer.

Time complexity of your code would be O(n)

Community
  • 1
  • 1
Prateek Gupta
  • 538
  • 2
  • 10
0

Is my thinking for the total number of operations in the code-snippet below valid? (Big-O notation)

No because Big-O is not about code operations at the level that you are counting them. To quote this descent page about Big-O:

Big O notation is used in Computer Science to describe the performance or complexity of an algorithm. Big O specifically describes the worst-case scenario, and can be used to describe the execution time required or the space used (e.g. in memory or on disk) by an algorithm.

In your case you have:

O(N) describes an algorithm whose performance will grow linearly and in direct proportion to the size of the input data set.

As N increases, your for loop increases linearly so your code is O(N).

Gray
  • 115,027
  • 24
  • 293
  • 354