This problem (named Hailstones) comes from Douglas Hofstadter

4 thoughts on “Problem 6”

/*
* 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.");
}
}

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.

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.

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 > 1 ) { /*i use "n>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 +".");
}
}
}

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.

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.

my method here: