• Post Reply Bookmark Topic Watch Topic
  • New Topic

Finding max value using if an while  RSS feed

 
Paul Phoenix
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Paul Clapham
Sheriff
Posts: 22508
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the "valueX" variable for?

And why aren't you considering all the elements of the series when you're looking for the largest element?
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, there are two errors in that bit of code, and I only noticed one of them.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!