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 🙂

<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 🙂

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