Hailstone sequence

From Fōrmulæ wiki
Jump to: navigation, search

This page is the answer to the task Hailstone sequence in the Rosetta Code.

Description (from Rosetta Code)

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

The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.

The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud), or as the Collatz sequence.

Task

  1. Create a routine to generate the hailstone sequence for a number.
  2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
  3. Show the number less than 100,000 which has the longest Hailstone sequence together with that sequence's length (But don't show the actual sequence!).

Routine

The same program when the flowchart package visualization is selected. Click/tap to enlarge

HailstoneSequenceCode.png

Case 1

Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1

HailstoneSequenceCase1.png

Note that the extraction of an element from a list with negative index means that it is counted from the end, it is, the is the last element, the is the penulatimate one, and so on.

Case 2

Show the number less than 100,000 which has the longest Hailstone sequence together with that sequence's length (But don't show the actual sequence!).

HailstoneSequenceCase2.png

The longest Hailstone sequence number is 77,031, having 351 elements.