Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to generate Hailstone Sequence in Java?

DZone's Guide to

How to generate Hailstone Sequence in Java?

· Java Zone ·
Free Resource

Atomist automates your software deliver experience. It's how modern teams deliver modern software.

Program Statement

How to generate Hailstone Sequence in Java?

Solution

The Hailstone sequence of numbers can be generated from a starting positive integer, n by:

  • If n is 1 then the sequence ends.
  • If n is even then the next n of the sequence = n/2
  • If n is odd then the next n of the sequence = (3 * n) + 1

Code

?
package com.skilledmonster.examples.operations;
import java.util.Scanner;
/**
* Program to generate Hailstone Sequence.
* This program reads a number from the user then displays the Hailstone sequence
* for that number followed by a line that shows the number of steps taken to reach 1.
*
* @author Jagadeesh Motamarri
* @version 1.0
*/
public class HailstoneSequenceGenerator {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
System.out.printf("Enter a Number:  ");
try {
int number = inputScanner.nextInt();
int steps = 0;
while (number != 1) {
if (number % 2 == 0) {
System.out.println(number + " is even, so I take half: " + number / 2);
number /= 2;
} else {
System.out.println(number + " is odd, so I make 3n + 1: " + (number * 3 + 1));
number = number * 3 + 1;
}
steps++;
}
System.out.println("The process took " + steps + (steps < 2 ? " step" : " steps") + " to reach 1");
} catch (Exception e) {
System.out.println("Not a Number!! Run your Program again <img src="http://www.skilledmonster.com/wp-includes/images/smilies/icon_smile.gif" alt=":-)" class="wp-smiley"> ");
}
}
}

Output

hailstone_sequence   

As shown in the console output, for interger 17, it took 12 steps to reach 1 using Hailstone Sequence.

References

http://en.wikipedia.org/wiki/Collatz_conjecture


Get the open source Atomist Software Delivery Machine and start automating your delivery right there on your own laptop, today!

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}