Home > Software design >  How to evaluate the x modulo y when x is not an int?
How to evaluate the x modulo y when x is not an int?

Time:03-06

How to evaluate something like 3/2 % 2?

Got stuck when solving the below problem:

What value does mystery(12) return?
  public int mystery(int x)
  {
       int n = 0;
       for (int k = x; k > 0; k = k / 2)
           if (k % 2 != 0) n  ;
       return n;
}

My working:

First execution
int k = 12/2, k = 6
6 % 2 returns 0, and so 6 % 2 != 0 evaluates as false, n = 0

Second execution
k = 6/2, k = 3
3 % 2 returns 1, and so 3 % 2 != 0 evaluates as true, n = 1

Third execution
k = 3/2, k = 1.5
1.5 % 2 ... not sure how to evaluate this and continue?

Thanks.

CodePudding user response:

  • k is of int type, the k = k / 2 expression is integer division hence 3/2=1, not 1.5
  • the value of k in first execution is 12, not 6 because k = k / 2 happens after body of loop
  • hence the k gets values 12,6,3,1,0 , of which the body of loop is executed four times, of which only 3 and 1 are odd hence n = 2
  • why don't you try it yourself?
  • if you declared values as doubles, the % operator would work for doubles - 1.5 % 2 is 1.5

CodePudding user response:

since k is an integer, it will be rounded down to 1. So, the third execution will return 1%2 = 1

The final answer will be 2

  • Related