How to resolve the algorithm Hailstone sequence step by step in the ALGOL-M programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Hailstone sequence step by step in the ALGOL-M 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 ALGOL-M programming language
Source code in the algol-m programming language
BEGIN
INTEGER N, LEN, YES, NO, LIMIT, LONGEST, NLONG;
% RETURN P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
% COMPUTE AND OPTIONALLY DISPLAY HAILSTONE SEQUENCE FOR N. %
% RETURN LENGTH OF SEQUENCE OR ZERO ON OVERFLOW. %
INTEGER FUNCTION HAILSTONE(N, DISPLAY);
INTEGER N, DISPLAY;
BEGIN
INTEGER LEN;
LEN := 1;
IF DISPLAY = 1 THEN WRITE("");
WHILE (N <> 1) AND (N > 0) DO
BEGIN
IF DISPLAY = 1 THEN WRITEON(N," ");
IF MOD(N,2) = 0 THEN
N := N / 2
ELSE
N := (N * 3) + 1;
LEN := LEN + 1;
END;
IF DISPLAY = 1 THEN WRITEON(N);
HAILSTONE := (IF N < 0 THEN 0 ELSE LEN);
END;
% EXERCISE THE FUNCTION %
YES := 1; NO := 0;
WRITE("DISPLAY HAILSTONE SEQUENCE FOR WHAT NUMBER?");
READ(N);
LEN := HAILSTONE(N, YES);
WRITE("SEQUENCE LENGTH =", LEN);
% FIND LONGEST SEQUENCE BEFORE OVERFLOW %
N := 2;
LONGEST := 1;
LEN := 2;
NLONG := 2;
LIMIT := 1000;
WRITE("SEARCHING FOR LONGEST SEQUENCE UP TO N =",LIMIT," ...");
WHILE (N < LIMIT) AND (LEN <> 0) DO
BEGIN
LEN := HAILSTONE(N, NO);
IF LEN > LONGEST THEN
BEGIN
LONGEST := LEN;
NLONG := N;
END;
N := N + 1;
END;
IF LEN = 0 THEN WRITE("SEARCH TERMINATED WITH OVERFLOW AT N =",N-1);
WRITE("MAXIMUM SEQUENCE LENGTH =", LONGEST, " FOR N =", NLONG);
END
You may also check:How to resolve the algorithm Fibonacci word/fractal step by step in the Fōrmulæ programming language
You may also check:How to resolve the algorithm Sum of a series step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Jensen's Device step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm Mertens function step by step in the APL programming language
You may also check:How to resolve the algorithm Ludic numbers step by step in the Elixir programming language