This program generates the Hailstone sequence (Collatz conjecture) of a number entered by the user.

Collatz conjecture at WikiPedia: Link.

In the Collatz conjecture, to find the next number in the sequence, we divide the current number by 2 if it is even or multiply it by 3 and add by 1 if it is odd.

So the sequence for number 6 would be: 6, 3, 10, 5, 16, 8, 4, 2, 1.

Program:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.Scanner; public class HailStone { static Scanner MyScanner = new Scanner(System.in); public static void main(String[] args) { System.out.println("This program will generate the HailStone sequence. "); System.out.println("Enter a number: "); int num = MyScanner.nextInt(); //Taking input from user while(num>1) { if (num%2 == 0) { num /= 2; //Dividing num by 2 if it is even System.out.print(num+"\t"); } else { num = (num*3)+ 1; // Adding num*3 + 1 to num if the num is odd System.out.print(num+"\t"); } } } } |

Tested in Eclipse.

The following two tabs change content below.

#### Vlad

#### Latest posts by Vlad (see all)

- Code jam “Tic-Tac-Toe-Tomek” solution in java - April 19, 2013
- Code jam “Minimum Scalar product” solution in java - March 18, 2013
- Code jam Store Credit solution in java - March 10, 2013