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. This sequence takes a number, and divides it by 2 if it is even, or multiplies it by three
- * and adds 1 if it is even, until the number hits one.
- */
- import acm.program.*;
- public class Hailstone extends ConsoleProgram
- {
- public void run()
- {
- int n = readInt("Enter a positive integer n: "); //This has the user enter the integer on which to compute the sequence
- if(n < 1) //This makes sure that the input is a positive integer. If it isn't, the program restarts.
- {
- println("That is not a positive integer. Try again.");
- run();
- }
- else
- {
- //This starts a count of the steps at 0
- int count = 0;
- //This loop keeps going until n hits 1.
- while(n > 1)
- {
- count++; //This adds to the count with each step
- int m = n; //This creates an integer m equal to n.
- if(n % 2 == 0) //If n is even (found by a mod test), then it divides it by two and tells us the result
- {
- n /= 2;
- println(m + " is even, so I take half: " + n);
- }
- else //Otherwise, it does 3n+1 and tells us the result
- {
- n = 3 * n + 1;
- println(m + " is odd, so I make 3n+1: " + n);
- }
- }
- println("\nIt took " + count + " steps to reach 1."); //Now it tells us the number of steps it took
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment