How to resolve the algorithm Hofstadter Q sequence step by step in the Modula-2 programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Hofstadter Q sequence step by step in the Modula-2 programming language

Table of Contents

Problem Statement

It is defined like the Fibonacci sequence, but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.

(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Hofstadter Q sequence step by step in the Modula-2 programming language

Source code in the modula-2 programming language

MODULE QSequence;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;

VAR n: CARDINAL;
    Q: ARRAY [1..1000] OF CARDINAL;
    
BEGIN
    Q[1] := 1;
    Q[2] := 1;
    FOR n := 3 TO 1000 DO
        Q[n] := Q[n-Q[n-1]] + Q[n-Q[n-2]];
    END;
    
    WriteString("The first 10 terms are:");
    FOR n := 1 TO 10 DO
        WriteCard(Q[n],2);
    END;
    WriteLn();
    
    WriteString("The 1000th term is:");
    WriteCard(Q[1000],4);
    WriteLn();
END QSequence.


  

You may also check:How to resolve the algorithm Sorting algorithms/Gnome sort step by step in the Haxe programming language
You may also check:How to resolve the algorithm Trigonometric functions step by step in the Erlang programming language
You may also check:How to resolve the algorithm Conway's Game of Life step by step in the Elena programming language
You may also check:How to resolve the algorithm Colour bars/Display step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Hilbert curve step by step in the Ada programming language