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

Learn how our document data model can map directly to how you program your app, and native database features like secondary indexes, geospatial and text search give you full access to your data. Brought to you in partnership with MongoDB.

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 when your data grows or your application performance demands increase, MongoDB Atlas allows you to scale out your deployment with an automated sharding process that ensures zero application downtime. Brought to you in partnership with MongoDB.

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