Skip to content

Instantly share code, notes, and snippets.

@NatashaTheRobot
Created November 2, 2011 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NatashaTheRobot/1332624 to your computer and use it in GitHub Desktop.
Save NatashaTheRobot/1332624 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link
Author

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