linuxid10t

revised Khalil code

Sep 3rd, 2011
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 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. This sequence takes a number, and divides it by 2 if it is even, or multiplies it by three
  6. * and adds 1 if it is even, until the number hits one.
  7. */
  8.  
  9. import acm.program.*;
  10.  
  11. public class Hailstone extends ConsoleProgram
  12. {
  13. public void run()
  14. {
  15. int n = readInt("Enter a positive integer n: "); //This has the user enter the integer on which to compute the sequence
  16. if(n < 1) //This makes sure that the input is a positive integer. If it isn't, the program restarts.
  17. {
  18. println("That is not a positive integer. Try again.");
  19. run();
  20. }
  21. else
  22. {
  23. //This starts a count of the steps at 0
  24. int count = 0;
  25. //This loop keeps going until n hits 1.
  26. while(n > 1)
  27. {
  28. count++; //This adds to the count with each step
  29. int m = n; //This creates an integer m equal to n.
  30. if(n % 2 == 0) //If n is even (found by a mod test), then it divides it by two and tells us the result
  31. {
  32. n /= 2;
  33. println(m + " is even, so I take half: " + n);
  34. }
  35. else //Otherwise, it does 3n+1 and tells us the result
  36. {
  37. n = 3 * n + 1;
  38. println(m + " is odd, so I make 3n+1: " + n);
  39. }
  40. }
  41. println("\nIt took " + count + " steps to reach 1."); //Now it tells us the number of steps it took
  42. }
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment