User:Thebigh/mysandbox

From Rosetta Code
Revision as of 10:22, 6 December 2020 by Thebigh (talk | contribs) (tweak)

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

a0 = 0

an+1 = 1/(2⌊an⌋+1-an) for n > 0

  • Show on this page terms 0 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type.


It is also possible, given a nonnegative 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:

[a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1]

Thus, for example, 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.

  • Find the position of the number 83116/51639 in the Calkin-Wilf sequence.
See also
  • Wikipedia entry: [[wp:Calkin–Wilf_tree|Calkin-Wilf tree]