Hello, I just started doing an online tutorial to learn some java and I'm stumped on solving this Hailstorm Problem. The problem is an old math phenomenon where no matter what number you start with you will end at the number 1. If the number is even you divide it by two and if its odd you compute 3n + 1 (n being the number) and you continue to do it until you reach 1. So here was my attempt at solving it:
import acm.program.*; public class Hailstone extends ConsoleProgram { public void run() { int n = readInt ("Enter a number: "); int turns = 1; while (n != 1) { if ((n % 2) == 0){ numEven(n); } else { numOdd(n); } turns++; } println ("The process took " + turns + " to reach 1."); } // numEven computes the answer if n is even. private int numEven (int n) { int j = n/2; println (n + " is even so I take half: " + j); return j; } // numOdd computes the answer if n is odd. private int numOdd (int n) { int k = (int)(n * 3) + 1; println (n + " is odd, so I make 3n + 1: "+ k); return k; } }
The problem being that its looping indefinitely after it solves the first even or odd computation and doesn't put the returned value back into the original n for the second loop. Let me know if you think of anything to solve this. Thanks.