The Gateway to Computer Science Excellence
+3 votes
193 views

Need some clarification regarding this answer Do comment please:
 

in Programming by Boss (11.9k points) | 193 views
0
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
should increments done to loop variables be included as they are also implicit addition?
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
i incrementing 20 times, j 400 times and k 8000 times.
0

yes.Got it now

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

should be 8420 

1 Answer

+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$

by Boss (16.2k points)
selected by
+1
Thanks !
0
The loop increment for first loop variable i should happen 21 times as last will result in failure condition?Same for j and k?
0
$\text{No Rahul :you are missing a point that i,j,k will bot be increamented  when }i=1,j=1,k=1 $
0
Got it.thank you!!Nice observation
0
You are welcome rahul :)

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,390 answers
198,589 comments
105,443 users