Consider the following algorithm. x ← 1 for i is in {1, 2, 3, 4} do for j is in {1, 2, 3, 4, 5} do x ← x + x for k is in {1, 2, 3} do x ← x + 1 x ← x + 5 Count the number of + operations done by this algorithm.
for each value i from 1 to 4, j has to go 1 to 5. Therefore \(x \gets x+x \) happens \(4\times 5=20\) times. for each value k from 1 to 3, \(x \gets x+1\) and \(x\gets x+5\) happens. Therefore in that loop summation occurs \(3\times 2=6\) times. Therefore all together there are 20+6=26 summations
hmm. I tried 26 and it was incorrect.. any ideas?
@BAdhi
are you sure that the loop which uses k is not inside the loop which uses i and are you sure that they are not asking for the final value of x
yeah now its a whole different story.(this is why I told you to use the indentation correctly) consider inner loops for one value of i, \(x\gets x+x\) happens 5 times and each \(x\gets x+1\) and \(x\gets x+5\) happens 3 times so all together \(5+3\times2=11\) times. This is just for one value of i. For each value of i from 1 to 4, above scenario repeats for 4 times, which gives us \(11\times 4=44\)
ok got it! thanks Badhi!
ur welcome:)
I don't get it!! where did you get the 2?
where did you get this question?? :P its a year old one
you mean \(5+3\times \color{red} 2\)
Join our real-time social learning platform and learn together with your friends!