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

Published on 12 May 2024 09:40 PM

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

Source code in the tcl programming language

package require Tcl 8.5

# Index 0 is not used, but putting it in makes the code a bit shorter
set tcl::mathfunc::Qcache {Q:-> 1 1}
proc tcl::mathfunc::Q {n} {
    variable Qcache
    if {$n >= [llength $Qcache]} {
	lappend Qcache [expr {Q($n - Q($n-1)) + Q($n - Q($n-2))}]
    }
    return [lindex $Qcache $n]
}

# Demonstration code
for {set i 1} {$i <= 10} {incr i} {
    puts "Q($i) == [expr {Q($i)}]"
}
# This runs very close to recursion limit...
puts "Q(1000) == [expr Q(1000)]"
# This code is OK, because the calculations are done step by step
set q [expr Q(1)]
for {set i 2} {$i <= 100000} {incr i} {
    incr count [expr {$q > [set q [expr {Q($i)}]]}]
}
puts "Q(i)<Q(i-1) for i \[2..100000\] is true $count times"


  

You may also check:How to resolve the algorithm Quoting constructs step by step in the BQN programming language
You may also check:How to resolve the algorithm Minimum positive multiple in base 10 using only 0 and 1 step by step in the Scala programming language
You may also check:How to resolve the algorithm Peano curve step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm Rosetta Code/Find bare lang tags step by step in the Ruby programming language
You may also check:How to resolve the algorithm Julia set step by step in the Raku programming language