The Hailstone path for an integer N is the sequence, of numbers generated by the Hailstone function begin at N and ending at 1. The Hailstone path length is the number of integers that appear on the Hailstone path, which is 1 plus the number of times the hailstone function is called to reach 1. i.e. h(n) = 1.
Such sequences are called hailstone sequences because the values typically rise and fall, somewhat analogously to a hailstone inside a cloud.
Program
Write a program to compute the Hailstone path of given N.
Input
- The number(N) for which the hailstone path is to be computed.
Output
- The total number in the path.
- The largest number in the path.
Example
For example, the Hailstone path for number 12 is 12, 6, 3, 10, 15, 16, 8, 4, 2, 1.
The total numbers in the hailstone path are: 10
The largest number in the hailstone path is: 16
Algorithm
For a given N, iterate using the following rule:
if N is an even number, the next number in the path is N = N/2, else N = 3N + 1.
Stop iterating the above rule, after the sequence 4, 2, 1 occurs.
Test cases
No | Input N (How many numbers) | Intermediate (Path) | Output (Total, Largest) |
---|---|---|---|
1 | 12 | 12, 6, 3, 10, 15, 16, 8, 4, 2, 1 | 10,16 |
2 | 3 | 3,10, 5, 16, 8, 4, 2, 1 | 8,16 |
3 | 7 | 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 | 17,52 |
Instructions
- Accept the number (N) for which the Hailstone path has to be computed as input via the command line arguments.
- Write the logic to compute the Hailstone numbers on the path, determine the length of the path along with the largest number in the path.
- Display the result i.e. Total and Largest separated by a comma.