0

How many instructions as a function of the input size N?

int count=0;
for (int i=0; i<N; i++)
  for(int j=i+1; j<N; j++)
    if(a[i] + a[j] ==0)
       count++;

# of "less than" compare instructions = 1/2(N+1)(N+2) Can someone pl. explain why there is 1/2 multiplier?

# of "equal to" compare instructions = 1/2 * N * (N-1). The same here why is there 1/2 * (N-1). Shouldn't it be just N?

also when do we increment j++?, after count++ or after we increment i?

Thank you!

David Richerby
  • 81,689
  • 26
  • 141
  • 235
Na Dia
  • 103
  • 2

2 Answers2

1

The factors of $\tfrac12$ come from the fact that $1 + \dots + N = \tfrac12N(N+1)$.

j is incremented at the end of the loop. This is standard syntax for languages such as C and Java.

David Richerby
  • 81,689
  • 26
  • 141
  • 235
0

Number of "equal to" compare instructions :

It is equal to the no of times inner for loop(with j variable) is executing.
For i=0: it is executing (N-1) times
For i=1: (N-2) times 
For i=(N-1) : (N-(N-1+1))=0 time.

So, total execution= (N-1)+(N-2)+.....+3+2+1+0=1/2 * N * (N-1)

Number of "less than" compare instructions:

There will be (N+1) number of comparison for outer for loop.
For inner loop:
  for i=0: N comparison
  for i=1: (N-1) comparison
  for i=N-2: 2 comparison
  for i=N-1: 1 comparison

Total number of comparisons= (N+1)+N+(N-1)+.....+2+1=1/2(N+1)(N+2) 
Mostafizar
  • 16
  • 2