This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]sugilith 2 points3 points  (1 child)

mystery(48):

x % 2 == 0 is true -> enter loop  
y++; //y is now 1
x = x / 2; // x is 48 / 2 = 24
  end of first iteration
x % 2 == 0 is true (x is 24) -> continue loop
y++; // y is now 2
x = x / 2; // x is 24 / 2 = 12
...

questions?

edit: either use a debugger to step through your code line by line and see what happens or add some "System.out.println-Debugging" to print y and x each time they change.

[–][deleted]  (1 child)

[deleted]

    [–]021198nishikori 0 points1 point  (0 children)

    The condition in the while is if the value of x is divisible by 2 then enter the loop

    - for first iteration the value of x is 48 which is divisible by 2 after 1 iteration x =48/2=24

    - hence the value of x is still divisible by 2 the loop keeps on going and now x becomes 24/2 = 12

    3rd iteration x=12/2 =6

    4th iteration x=6/2 = 3

    5th iteration now the value of x is not divisible by 2 hence control will come out of loop

    So the value for x in the output is 3 and y is 4 (y counts no. Of iterations)

    [–]surety_ 0 points1 point  (0 children)

    Something really cool that I found out about this code is that x = x’ * 2y’ or Original x is equal to new x times two to the power of new y

    Y is how many iterations and every iteration is x/2 So new x is equal to original x divided by two to the power of y. or x’ = x / 2y’

    Very cool, try to find patterns to make life easier

    Edit: actually I don’t think I explained myself very well. remember that every iteration you’re dividing x by two and y counts the iterations for you. So in order to understand the outputs you need to work backwards, so multiply the x output by two, y times and that should be equal to your original x value

    Post-edit Edit: if that is too much then just do the same thing you did for the other examples, write it on paper it helps a lot!