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

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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


Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

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 }}