Advertisement
krystation

HailStone

Jul 20th, 2012
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. /*
  2.  * File: Hailstone.java
  3.  * --------------------
  4.  * This program is a stub for the Hailstone problem, which computes
  5.  * Hailstone sequence described in Assignment #2.
  6.  */
  7.  
  8. import acm.program.*;
  9.  
  10. public class Hailstone extends ConsoleProgram {
  11.        
  12.     public void run() {
  13.         println("This program shows the Hailstone sequence ");
  14.         println("and tells you how many steps it takes to reach the number 1");
  15.         println("");
  16.         int n=readInt("Enter a possitive integer:");
  17.         int numberOfSteps=0;//keeps track of the number of steps, starts at 0
  18.         if (n==1){
  19.             println("Seriously...");
  20.         }
  21.         if (n==0){
  22.             println("Ahh!!! ERROR!! ERROR!! ERROR!!");
  23.             n=1;
  24.         }
  25.         while (n!=1){//will do this until n becomes 1
  26.             if (n%2==0){//checks to see if n is even.
  27.                 int n1=n;//n1 saves the value of integer 'n' before it changes again
  28.                 n/=2;//takes half of n if n is even
  29.                 println(n1+" is even so take half:"+n);
  30.                 println("");
  31.             } else {
  32.                 int n1=n;
  33.                 n=n*3+1;// if n is odd, it multiplies it by three and adds 1
  34.                 println(n1+" is odd so I make 3n+1:"+n);
  35.                 println("");
  36.             }
  37.             numberOfSteps++;
  38.         }
  39.         println("This process took " +numberOfSteps+ " steps to reach 1.");
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement