Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * File: Hailstone.java
- * --------------------
- * This program is a stub for the Hailstone problem, which computes
- * Hailstone sequence described in Assignment #2.
- */
- import acm.program.*;
- public class Hailstone extends ConsoleProgram {
- public void run() {
- println("This program shows the Hailstone sequence ");
- println("and tells you how many steps it takes to reach the number 1");
- println("");
- int n=readInt("Enter a possitive integer:");
- int numberOfSteps=0;//keeps track of the number of steps, starts at 0
- if (n==1){
- println("Seriously...");
- }
- if (n==0){
- println("Ahh!!! ERROR!! ERROR!! ERROR!!");
- n=1;
- }
- while (n!=1){//will do this until n becomes 1
- if (n%2==0){//checks to see if n is even.
- int n1=n;//n1 saves the value of integer 'n' before it changes again
- n/=2;//takes half of n if n is even
- println(n1+" is even so take half:"+n);
- println("");
- } else {
- int n1=n;
- n=n*3+1;// if n is odd, it multiplies it by three and adds 1
- println(n1+" is odd so I make 3n+1:"+n);
- println("");
- }
- numberOfSteps++;
- }
- println("This process took " +numberOfSteps+ " steps to reach 1.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement