484 views
0 votes
0 votes
Consider the following program fragments

d=0;

for(i=1;i<31;++i)

for(j=1;j<31;++j)

for(k=1;k<31;++k)

if(((i+j+k)%3)==0)

d=d+1;

print("%d",d);

Q.1     The output will be

           (a)9000  (b)27000  (c)3000  (d)None

Q.2    The number of addition performed by the above program fragment is

           (a)27000  (b)27000 * 3  (c)9000 + 3 * 27000  (d)9930 + 27000 * 3

 

#   * multiplication in above Q.2 options

#Answer given in the answer key are  Q.1 (a)   Q.2 (d)#

please explain it.......:)

1 Answer

1 votes
1 votes
a+b+c = 3

Case 1: if (a+b+c) % 3 = 0

3 , 6, 9 , 12,15,18,21,24,27 ,30 =  $\binom{10}{1}$  we can choose for a ,b , c independently

therefore ,   $\binom{10}{1}$  $\binom{10}{1}$  $\binom{10}{1}$   =  1000 ways

 

Case 2:  if  a, b, and c all leave a remainder 1 so that a + b + c is evenly divisible by 3

1 , 4, 7, 10, 13, 16, 19, 22 , 25 , 28

i:e  1+4+10 = 15 , 1+1+1 = 3 etc etc

Now fixed i=1  and change j and k respt

 

as we fixed i=1

when (i+j)% = 1 we choose the value of k from the set {1 , 4, 7, 10, 13, 16, 19, 22 , 25 , 28}

when (i+j)% = 0 we choose the value of k from the set  {3 , 6, 9 , 12,15,18,21,24,27 ,30}

Now observe that for every value of j there's a 10 values for K which satisfies the condition : (a+b+c) %3 = 0

therefore j iterate 30 times and in each iteration there's a 10 values for k that satisfy (i+j+k) % 3 = 0

therefore  300 times d=d+1 execute ; therefore d= 300

similarly when i = 2 ,  again  300 times d=d+1 execute ; therefore d= 600

similarly i iterates 30 times

in each iteration d execute 300 times

therefore d=d+1  execute 300 *30 = 9000

therefore answer is 9000

No related questions found