Jeff Verdegan wrote:
Haani Naz wrote:So i believe the 2nd one (below) will finish. Seeing how n only increments by 1 and i will multiplication of its own value - at some point it will be greater than n. I am right correct?
Yes, it will finish, but your reasoning applies more to actual integers than to Java ints or longs. (And, like I said, unless you come back and tell me otherwise, I'm going to assume we're dealing with Java primtives here.)
One very simple way to answer this question is to keep in mind that multiplying an int by 2 is the same as doing a bitwise left-shift of 1.
Think about what happens to the bit pattern when you do that. Better yet, follow Campbell's suggestion and work it out on pencil and paper. Do it with a single 8-bit byte to make your life simpler.
Campbell Ritchie wrote:What about No 2: What if you start with n = 2000000000;? What will happen then?
Go through the execution with pencil and paper for 32 iterations and tell us the values of i and n at that stage. Then work out whether the loop will terminate.
Jeff Verdegan wrote:
Haani Naz wrote:
Jeff Verdegan wrote:I will say, though, that the last one looks like it might be the Collatz conjecture.
Thanks did a look up on that and i found my answer. Will focus on the 2nd one now!
Be careful though. If you start Collatz with, say 987654321 on paper you will NOT get the same next value as you will in Java.
Also, did you figure out the case where the first one never finishes?
Jeff Verdegan wrote:I will say, though, that the last one looks like it might be the Collatz conjecture.
Ernest Friedman-Hill wrote:Look at these three lines very carefully:
Notice anything wrong?
Jesper de Jong wrote:
Haani Naz wrote:This fails to work - i get run time errors.
Please tell us exactly what those errors are, that would make it a lot easier to help you find the cause.