recategorized by
966 views
1 votes
1 votes

Given the pseudocode below for the function $\textbf{remains()}$, which of the following statements is true about the output, if we pass it a positive integer $n>2$?

int remains(int n)
{  
     int x = n;
     for (i=(n-1);i>1;i--)  {
        x = x % i ;
   }
     return x;
}
  1. Output is always $0$
  2. Output is always $1$
  3. Output is $0$ only if $n$ is NOT a prime number
  4. Output is $1$ only if $n$ is a prime number
  5. None of the above
recategorized by

2 Answers

3 votes
3 votes

BASIC point :-

1%1 = 0

1% x = 1, for x > 1

x+1%x = 1, for all x.


 

for(i=(n-1);i>1;i--)
    x=x%i;

when i=(n-1) ===> x will updated to 1 due to x%i returns 1

after that it never changed.

if i=1, then x will updated to 0 but when i=1, condition evaluates to false, So x can't updated one more time.

1 votes
1 votes
loop continues from n-1  down to 2.
in first iteration
x%i become n%(n-1).
and  which results in  1 for any value of n>=2
and after first iteration x will become 1 and then x%i will always results 1  ( for i>1)
Answer:

Related questions

3 votes
3 votes
1 answer
3