How to resolve the algorithm Hofstadter Q sequence step by step in the Cowgol programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Hofstadter Q sequence step by step in the Cowgol 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 Cowgol programming language
Source code in the cowgol programming language
include "cowgol.coh";
# Generate 1000 terms of the Q sequence
var Q: uint16[1001];
Q[1] := 1;
Q[2] := 1;
var n: @indexof Q := 3;
while n <= 1000 loop
Q[n] := Q[n-Q[n-1]] + Q[n-Q[n-2]];
n := n + 1;
end loop;
# Print first 10 terms
print("The first 10 terms are: ");
n := 1;
while n <= 10 loop
print_i16(Q[n]);
print_char(' ');
n := n + 1;
end loop;
print_nl();
# Print 1000th term
print("The 1000th term is: ");
print_i16(Q[1000]);
print_nl();
You may also check:How to resolve the algorithm Generic swap step by step in the Modula-3 programming language
You may also check:How to resolve the algorithm Sorting algorithms/Bogosort step by step in the SNOBOL4 programming language
You may also check:How to resolve the algorithm Doomsday rule step by step in the Raku programming language
You may also check:How to resolve the algorithm Averages/Root mean square step by step in the Futhark programming language
You may also check:How to resolve the algorithm Copy a string step by step in the Déjà Vu programming language