How to resolve the algorithm Hailstone sequence step by step in the Icon and Unicon programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Hailstone sequence step by step in the Icon and Unicon programming language

Table of Contents

Problem Statement

The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:

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

This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):

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).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Hailstone sequence step by step in the Icon and Unicon programming language

Source code in the icon programming language

procedure hailstone(n)
    while n > 1 do {
        suspend n
        n := if n%2 = 0 then n/2 else 3*n+1
        }
    suspend 1
end


procedure main(args)
    n := integer(!args) | 27
    every writes(" ",hailstone(n))
end


procedure hailstone(n)
    static cache
    initial {
        cache := table()
        cache[1] := [1]
        }
    /cache[n] := [n] ||| hailstone(if n%2 = 0 then n/2 else 3*n+1)
    return cache[n]
end


procedure main(args)
    n := integer(!args) | 27
    task2(n)
    write()
    task3()
end

procedure task2(n)
    count := 0
    every writes(" ",right(!(sequence := hailstone(n)),5)) do
        if (count +:= 1) % 15 = 0 then write()
    write()
    write(*sequence," value",(*sequence=1,"")|"s"," in the sequence.")
end

procedure task3()
    maxHS := 0
    every n := 1 to 100000 do {
        count := *hailstone(n)
        if maxHS <:= count then maxN := n
        }
    write(maxN," has a sequence of ",maxHS," values")
end


  

You may also check:How to resolve the algorithm Last Friday of each month step by step in the D programming language
You may also check:How to resolve the algorithm LZW compression step by step in the Xojo programming language
You may also check:How to resolve the algorithm Long multiplication step by step in the Lobster programming language
You may also check:How to resolve the algorithm Forward difference step by step in the Plain English programming language
You may also check:How to resolve the algorithm Trigonometric functions step by step in the Clojure programming language