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

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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


Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Jagadeesh Motamarri, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}