nth Rational number in Calkin-Wilf sequence
Last Updated :
20 Mar, 2023
What is Calkin Wilf Sequence?
A Calkin-Wilf tree (or sequence) is a special binary tree which is obtained by starting with the fraction 1/1 and adding a/(a+b) and (a+b)/b iteratively below each fraction a/b. This tree generates every rational number. Writing out the terms in a sequence gives 1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, 2/5, 5/3, 3/4, 4/1, …The sequence has the property that each denominator is the next numerator.
The image above is the Calkin-Wilf Tree where all the rational numbers are listed. The children of a node a/b is calculated as a/(a+b) and (a+b)/b.
The task is to find the nth rational number in breadth first traversal of this tree.
Examples:
Input : 13
Output : [5, 3]
Input : 5
Output : [3, 2]
Explanation:
This tree is a Perfect Binary Search tree and we need floor(log(n)) steps to compute nth rational number. The concept is similar to searching in a binary search tree. Given n we keep dividing it by 2 until we get 0. We return fraction at each stage in the following manner:
if n%2 == 0
update frac[1]+=frac[0]
else
update frac[0]+=frac[1]
Below is the program to find the nth number in Calkin Wilf sequence:
C++
# include<bits/stdc++.h>
using namespace std;
int frac[] = {0, 1};
int nthRational( int n)
{
if (n > 0)
nthRational(n / 2);
frac[~n & 1] += frac[n & 1];
}
int main()
{
int n = 13;
nthRational(n);
cout << "[" << frac[0] << ","
<< frac[1] << "]" << endl;
return 0;
}
|
Java
import java.util.*;
public class GFG {
static int [] frac = { 0 , 1 };
public static void main(String args[])
{
int n = 13 ;
System.out.println(Arrays.toString(nthRational(n)));
}
static int [] nthRational( int n)
{
if (n > 0 )
nthRational(n / 2 );
frac[~n & 1 ] += frac[n & 1 ];
return frac;
}
}
|
Python3
frac = [ 0 , 1 ]
def nthRational(n):
if n > 0 :
nthRational( int (n / 2 ))
frac[~n & 1 ] + = frac[n & 1 ]
return frac
if __name__ = = "__main__" :
n = 13
print (nthRational(n))
|
C#
using System;
class GFG
{
static int [] frac = { 0, 1 };
public static void Main(String []args)
{
int n = 13;
Console.WriteLine( "[" + String.Join( "," ,
nthRational(n)) + "]" );
}
static int [] nthRational( int n)
{
if (n > 0)
nthRational(n / 2);
frac[~n & 1] += frac[n & 1];
return frac;
}
}
|
Javascript
<script>
let frac = [0, 1];
let n = 13;
document.write(`[${nthRational(n)}]`)
function nthRational(n) {
if (n > 0)
nthRational(Math.floor(n / 2));
frac[~n & 1] += frac[n & 1];
return frac;
}
</script>
|
Time complexity : O(log(n))
Auxiliary Space : O(1)
Explanation:
For n = 13,
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...