I’m pretty proud to say, that this one took me about 20-30 minutes to complete ðŸ™‚ It didn’t look easy initially (that’s why I waited all the way till the end to start it), but after doing the Find Range one, this one was a piece of cake! Here is the problem:

Here is my solution, also available on gist:

The hardest part of this problem was remembering to use the if / else statement instead of to “if” statements, since the first time I ran this, the operation continued to execute both of the “if” statements each time through the loop. Also, remember that an even number will not have a remainder when divided by 2 – hence the n%2 if statement for even numbers ðŸ™‚

<pre>/* * File: Hailstone.java * Name: * Section Leader: * -------------------- * This file is the starter file for the Hailstone problem. */ import acm.program.*; public class Hailstone extends ConsoleProgram { public void run() { int n = readInt("?"); //ask user for initial number input int steps = 0; //store the number of steps it takes to get to 1 while ( n != 1 ) { if ( n%2 == 0) { //if the remainder of n/2 is 0, then the number is even println (n + " is even, so I take half: " + n/2); n = (n/2); steps = steps + 1; } else { println (n + " is odd, so I make 3n+1: " + (3*n+1)); n = (3*n +1); steps = steps + 1; } } println ("The process took " + steps + " to reach 1"); } }</pre>

Ok, now moving on to bigger and greater things in Java ðŸ™‚

Hi! I ended up with a solution as good as identical to yours. Here it is:

Awesome!

Just want to point out that you might need to have a special case for the case where the input = 1. The idea is to have operations on any positive integer until they reach 1– which means this should be applicable to 1 itself as well. In the current program it would say took 0 steps to reach 1, but that would be logically inaccurate since you are also suppose to perform operations on 1 until it reaches 1.

Thanks for letting me know! Not everything I publish is the best solution, so I love getting feedback.

I decide to take the program to a tiny little extra level (feeling actually kinda happy with myself on this one, as i achieved it without help)

The program tests if its true! that there is no number that can simplified… Clearly this method i am using is not practical to be implemented but it does show proof of concept.. and it can easily be tweaked to actually serve the function to search for such a number…. feedback would be super welcome

Hi Natasha,

My solutions looks a bit different from yours:

I’ve just been programming for like a month, so I dunno if my idea was not good… could you give me a help? =)

Thats a clever solution. Great job!

thank you for your reply =)

Here’s my solution. It’s similar to yours, but it takes care of some other special cases, like if n=1 or 0.

http://pastebin.com/Rnh0gxtj