posted 6 years ago

Hello. What I've been trying to do is compute a hailstone series which is if the user input is even it will equal (answer=x/2) and if it is odd it will equal (answer=x*3+1) until it reaches 1. What I'm trying to do is find out the max value using only if and while statements and I can't seem to figure it out yet after playing around with it. This is what I have so far.

any ideas?

any ideas?

posted 6 years ago

you should indent your code better, and leave spaces around binary operators. That makes it much easier to read.

You need to go through the loop with a pencil and paper, and check all the places where there are > and < comparisons. Check carefully what you are comparing with. What are the values of valueX and maxValue when you do those comparisons?

You need to go through the loop with a pencil and paper, and check all the places where there are > and < comparisons. Check carefully what you are comparing with. What are the values of valueX and maxValue when you do those comparisons?

posted 6 years ago

That's not doing what you expect. If x is even then it will be divided by 2. If it's odd it will not be multiplied by 3 and have 1 added; it will be multiplied by 3, have 1 added, and then again be divided by 2.

If x is odd (x % 2 == 1) it will be multiplied by 3. That gives another odd number. 1 is then added, making the number even. You then check if x is even (x % 2 == 0) which it will now always be; if it was even before it wasn't changed and if it was odd it's even now.

I think you want to use an else instead:

That still gives you a result of 20 though. The 52 you are looking for will be the value of x after one loop iteration. But x != 1 so it will try again, halving the 52 into 26. It will then try again, again halving, etc.

Paul Phoenix wrote:

That's not doing what you expect. If x is even then it will be divided by 2. If it's odd it will not be multiplied by 3 and have 1 added; it will be multiplied by 3, have 1 added, and then again be divided by 2.

If x is odd (x % 2 == 1) it will be multiplied by 3. That gives another odd number. 1 is then added, making the number even. You then check if x is even (x % 2 == 0) which it will now always be; if it was even before it wasn't changed and if it was odd it's even now.

I think you want to use an else instead:

That still gives you a result of 20 though. The 52 you are looking for will be the value of x after one loop iteration. But x != 1 so it will try again, halving the 52 into 26. It will then try again, again halving, etc.

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6

How To Ask Questions How To Answer Questions