How to resolve the algorithm Hofstadter Q sequence step by step in the ERRE programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Hofstadter Q sequence step by step in the ERRE 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 ERRE programming language

Source code in the erre programming language

PROGRAM HOFSTADER_Q

!
! for rosettacode.org
!

DIM Q%[10000]

PROCEDURE QSEQUENCE(Q,FLAG%->SEQ$)
! if FLAG% is true accumulate sequence in SEQ$
! (attention to string var lenght=255)
! otherwise calculate values in Q%[] only

  LOCAL N
  Q%[1]=1
  Q%[2]=1
  SEQ$="1 1"
  IF NOT FLAG% THEN Q=NUM END IF
  FOR N=3 TO Q DO
    Q%[N]=Q%[N-Q%[N-1]]+Q%[N-Q%[N-2]]
    IF FLAG% THEN SEQ$=SEQ$+STR$(Q%[N]) END IF
  END FOR
END PROCEDURE

BEGIN
  NUM=10000
  QSEQUENCE(10,TRUE->SEQ$)
  PRINT("Q-sequence(1..10) : ";SEQ$)
  QSEQUENCE(1000,FALSE->SEQ$)
  PRINT("1000th number of Q sequence : ";Q%[1000])
  FOR N=2 TO NUM DO
    IF Q%[N]
  END FOR
  PRINT("Number of Q(n)
END PROGRAM

  

You may also check:How to resolve the algorithm Matrix transposition step by step in the Clojure programming language
You may also check:How to resolve the algorithm Find the intersection of two lines step by step in the zkl programming language
You may also check:How to resolve the algorithm McNuggets problem step by step in the CLU programming language
You may also check:How to resolve the algorithm Caesar cipher step by step in the C programming language
You may also check:How to resolve the algorithm Pascal's triangle step by step in the IDL programming language