How to resolve the algorithm Calkin-Wilf sequence step by step in the Bracmat programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Calkin-Wilf sequence step by step in the Bracmat programming language

Table of Contents

Problem Statement

The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows:

To avoid floating point error, you may want to use a rational number data type.

It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:

The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Calkin-Wilf sequence step by step in the Bracmat programming language

Source code in the bracmat programming language

( 1:?a
& 0:?i
&   whl
  ' ( 1+!i:<20:?i
    & (2*div$(!a,1)+1+-1*!a)^-1:?a
    & out$!a
    )
& ( r2cf
  =   floor
    .   div$(!arg,1):?floor
      & ( !floor:!arg
        | !floor r2cf$((!arg+-1*!floor)^-1)
        )
  )
& ( get-term-num
  =   ans dig pwr
    .   (0,1,1):(?ans,?dig,?pwr)
      & r2cf$!arg:?n
      &   map
        $ ( (
            =
              .     whl
                  ' ( !arg+-1:~<0:?arg
                    & !dig*!pwr+!ans:?ans
                    & 2*!pwr:?pwr
                    )
                & 1+-1*!dig:?dig
            )
          . !n
          )
      & !ans
  )
& out$(get-term-num$83116/51639)
);

  

You may also check:How to resolve the algorithm Wagstaff primes step by step in the Craft Basic programming language
You may also check:How to resolve the algorithm Multiple distinct objects step by step in the Logtalk programming language
You may also check:How to resolve the algorithm Convert seconds to compound duration step by step in the Sidef programming language
You may also check:How to resolve the algorithm Vigenère cipher/Cryptanalysis step by step in the C++ programming language
You may also check:How to resolve the algorithm Read a specific line from a file step by step in the Ring programming language