Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is the solution to the Hailstone problem from Assignment 2 of the Stanford CS106A Introduction to Programming Methodology Class
/*
* 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++;
}
else {
println (n + " is odd, so I make 3n+1: " + (3*n+1));
n = (3*n +1);
steps++;
}
}
println ("The process took " + steps + " to reach 1");
}
}
@NatashaTheRobot

This comment has been minimized.

Copy link
Owner Author

commented Feb 3, 2012

Thanks for the tip :) I've learned that since writing this, but as a real newbie, it was easier for me to write out steps = steps + 1 than steps++ or steps +=1, because it was easier for me to understand what was going on. Either way, corrected it here.

@NatashaTheRobot

This comment has been minimized.

Copy link
Owner Author

commented Feb 5, 2012

Thant definitely makes a lot of sense. Thanks for the thorough explanation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.