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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Calkin-Wilf sequence step by step in the Raku 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 Raku programming language

Source code in the raku programming language

my @calkin-wilf = Any, 1, {1 / (.Int × 2 + 1 - $_)} … *;

# Rational to Calkin-Wilf index
sub r2cw (Rat $rat) { :2( join '', flat (flat (1,0) xx *) Zxx reverse r2cf $rat ) }

# The task

say "First twenty terms of the Calkin-Wilf sequence: ",
    @calkin-wilf[1..20]».&prat.join: ', ';

say "\n99991st through 100000th: ",
    (my @tests = @calkin-wilf[99_991 .. 100_000])».&prat.join: ', ';

say "\nCheck reversibility: ", @tests».Rat».&r2cw.join: ', ';

say "\n83116/51639 is at index: ", r2cw 83116/51639;


# Helper subs
sub r2cf (Rat $rat is copy) { # Rational to continued fraction
    gather loop {
	    $rat -= take $rat.floor;
	    last if !$rat;
	    $rat = 1 / $rat;
    }
}

sub prat ($num) { # pretty Rat
    return $num unless $num ~~ Rat|FatRat;
    return $num.numerator if $num.denominator == 1;
    $num.nude.join: '/';
}


  

You may also check:How to resolve the algorithm Ordered words step by step in the Phix programming language
You may also check:How to resolve the algorithm Gaussian elimination step by step in the Ruby programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the E programming language
You may also check:How to resolve the algorithm Zero to the zero power step by step in the Bracmat programming language
You may also check:How to resolve the algorithm Square form factorization step by step in the Pascal programming language