Created
November 2, 2011 01:46
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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"); | |
} | |
} |
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
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.