retagged by
595 views
2 votes
2 votes

In the code fragment given below, $\mathsf{start}$ and $\mathsf{end}$ are integer values and $\mathsf{prime(x)}$ is a function that returns $\mathsf{true}$ if $\mathsf{x}$ is a prime number and $\mathsf{false}$ otherwise.

i:=0; j:=0; k:=0;
from (m := start;
      m <= end;
      m := m+1){
    if (prime(m)){
        i := i+m;
        k := k-m;
    }else{
        j :=j-m;
        k := k+m;
    }
}

At the end of the loop:

  1. $k == i-j.$
  2. $k == j-i.$
  3. $k == -j-i.$
  4. Depends on $\mathsf{start}$ and $\mathsf{end}$
retagged by

3 Answers

2 votes
2 votes
Let S denote the set of integers, [start, end]

Let x be the number of primes in S and y be the number of non-primes in S.

At the end of the execution,

i = x*m (Incremented for each prime)

j = -y*m (Decremented for each non-prime)

k = -x*m + y*m (Decremented for each prime and Incremented for each non-prime)

Therefore, k = -i - j

Hence the answer is (C)
0 votes
0 votes
Let start = 4 & end = 4 ; therefore  m =4 , we know 4 is not a Prime hence goes to else part. Now, j becomes -4 & k becomes 4. & loop stops. If we check options now, option b) is eliminated while a) & b) come as true.

Lets now take start =4 & end =5. Therefore m = 4, same happens as above & values in j=-4 &. k=4.

Now m++, & m becomes 5, for m=5, we will get True as m is a prime, so if() part works. Now, i becomes 5 & k becomes -1. Now, we check options, only option c) satisfies.

To verify once again, we can go from 4 to 6 & check so on. We can take start & end as any random numbers & it still satisfies. Hence we can eliminated d) i.e. it is independent of the values of start & end.
Answer:

Related questions

1 votes
1 votes
2 answers
3