4 thoughts on “Problem 6”

  1. /*
     * File: Hailstone.java
     * Name: 
     * Section Leader: 
     * --------------------
     * This file is the starter file for the Hailstone problem.
     */
     
    import acm.program.*;
     
    public class Hailstone extends ConsoleProgram {
    	private static final int THE_END = 1;
     
    	private int a = 0;
    	private int counter = 0;
     
    	public void run() {
     
    	a = readInt("Enter a number: ");	
     
    	while (a!=THE_END){
    		counter++;
    		if (a%2==0){
    			//for even number
    			a=a/2;
    			println(a + " is even, so I take half: "+a);
    		} else {
    			//for odd number
    			a=(a*3)+1;
    			println(a + " is odd, so I make 3n+1: "+a);
    		}
    	}	
    		println ("It took " + counter +" times.");
    	}
    }
  2. If you enter a negative integer or zero, it goes into an infinite loop.

    if(input <= 0) {break;}

    Richard Curtis, you are displaying the same integer twice.

  3. I think the infinite loop caused by zero or negative integer can be avoided just by changing
    while(n != 1) to while(n > 1)
    this will be better, i guess.

  4. my method here:

    /*
     * File: Hailstone.java
     * Name: 
     * Section Leader: 
     * --------------------
     * This file is the starter file for the Hailstone problem.
     */
     
    import acm.program.*;
     
    public class Hailstone extends ConsoleProgram {
    	public void run() {
    		while (true){
    			int n,m,steps;
    			steps = 0;
    			m = 0;
    			n = readInt("Enter a number ");
    			while (n &gt; 1 ) {	/*i use "n&gt;1" instead of "n!=1"just to make
    								sure the program won't run infinitely*/
    				steps++;
    				/*Even*/
    				if ((n%2) == 0) {
    					m = n/2;
    					println(n +" is even, so it's devided by two :" + m);
    					n = m;
    				} else {
    					/*odd*/
    					m = n*3+1;
    					println(n +" is odd, so i make 3n+1 :" +m);
    					n = m;
    			}
    		}
    		println("The program takes " + steps + " to reach " + n +".");
    		}
    	}
    }

Leave a Reply

Your email address will not be published. Required fields are marked *