in Programming in C
737 views
3 votes
3 votes

Need some clarification regarding this answer Do comment please:
 

in Programming in C
737 views

5 Comments

Doubts :
If the sum is even then only we are incrementing the value thus there is always be half the total no of iteration where number (which is the total sum) will be even. Thus total iteration will be :
20*20*20=8000/2=4000?
Please suggest a better way to solve it.
0
0
should increments done to loop variables be included as they are also implicit addition?
0
0

@saxena0612

The question is not asking the number of times d = d + 1 is executed.Question says to find the number of additions preformed by code.So you need to consider all additions ( ++i,++j,++k,i+j+k,d=d+1).

Total Number of execution of  ++i , ++j and ++k add to 8000. Expression 

if( ( (i+j+k) %2 ) ==0 ) is also executed 8000 times but it has two additions.So another 16000 addition due to this. d = d +1 will contribute 4000 additions as you mentioned.So total of 28000 addition.

But the given answer is 28420 .I don't know where that 420 additions are coming from.Either I am missing something/doing something wrong or that j=1 in j for loop should have been j =0.

Note- there is a parenthesis miss match in the if statement.

0
0
i incrementing 20 times, j 400 times and k 8000 times.
0
0

yes.Got it now

Total Number of execution of  ++i , ++j and ++k add to 8000

should be 8420 

0
0

1 Answer

8 votes
8 votes
Best answer

There are $6$ instances of addition

  • $i++$
  • $j++$
  • $k++$
  • $i+j(\text{let it be s})$
  • $s+k$
  • $d+1$

We have to count how many times each of them is calculated.

d=d+1

First of all we will calculate number of additions of $d+1$, it will on the other hand signify the overall time complexity of the code.

it will be $\frac{n \times n \times n }{2}=O(n^3) \Rightarrow \frac{20 \times 20 \times 20 }{2} =4000$


i+j+k

Number of addition =$2 \times n \times n \times n=16000$


i++

$20 \text{times}$


j++

$20 \times 20=400\text{times}$


k++

$20 \times 20 \times 20=8000\text{times}$


Total number of additions$=4000+16000+20+400+8000=28420$

selected by

4 Comments

$\text{No Rahul :you are missing a point that i,j,k will bot be increamented  when }i=1,j=1,k=1 $
0
0
Got it.thank you!!Nice observation
0
0
You are welcome rahul :)
0
0

Related questions