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.
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+=frac else update frac+=frac
Below is the program to find the nth number in Calkin Wilf sequence:
For n = 13,
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Improved By : Harshit Saini
- Difference between Deterministic and Non-deterministic Algorithms
- Finding the Parity of a number Efficiently
- Minimum number of changes required to make the given array an AP
- Prim’s Algorithm (Simple Implementation for Adjacency Matrix Representation)
- Maximize the total profit of all the persons
- Vizing’s Theorem
- Count of numbers appearing in the given ranges at-least K times
- Pair with minimum absolute difference after solving each query
- Majority Element | Set-2 (Misra-Gries Family of Algorithms)
- Print all the combinations of a string in lexicographical order