# Stanford CS106A Assignment 2 Hailstone Solution

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 ðŸ™‚

```&lt;pre&gt;/*
* File: Hailstone.java
* Name:
* --------------------
* This file is the starter file for the Hailstone problem.
*/

import acm.program.*;

public class Hailstone extends ConsoleProgram {
public void run() {
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 + &quot; is even, so I take half: &quot; + n/2);
n = (n/2);
steps = steps + 1;
}
else {
println (n + &quot; is odd, so I make 3n+1: &quot; + (3*n+1));
n = (3*n +1);
steps = steps + 1;
}
}
println (&quot;The process took &quot; + steps + &quot; to reach 1&quot;);
}
}&lt;/pre&gt;
```

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

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.