Problem C
The Stern-Brocot Number System
Input: standard input
Output: standard output
The Stern-Brocot tree is a beautiful way for constructing the set ofall nonnegative fractions m / n where m and n are relativelyprime. The idea is to start with two fractions and then repeat thefollowing operations as many times as desired:
Insert between two adjacentfractions
and
.
For example, thefirst step gives us one new entry between and
,
and the nextgives two more:
The next givesfour more,
and then we willget 8, 16, and so on. The entire array can be regarded as an infinite binarytree structure whose top levels look like this:
The constructionpreserves order, and we couldn't possibly get the same fraction in twodifferent places.
We can, in fact,regard the Stern-Brocot tree as a number system for representing rationalnumbers, because each positive, reduced fraction occurs exactly once. Let's usethe letters L and R to stand for going down to the left orright branch as we proceed from the root of the tree to a particular fraction;then a string of L's and R's uniquely identifies a place in thetree. For example, LRRL means that wego left from down to
, then right to
, then right to
, then left to
. We can consider LRRLto be a representation of
. Every positive fraction gets represented in this way as aunique string of L's and R's.
Well, actuallythere's a slight problem: The fraction corresponds to the empty string, and we need a notation forthat. Let's agree to call it I,because that looks something like 1 and it stands for "identity".
In this problem,given a positive rational fraction, you are expected to represent it in Stern-Brocot number system.
Input
The input file contains multipletest cases. Each test case consists of a line contains two positive integers m and n where m and n are relatively prime. The inputterminates with a test case containing two 1's for m and n, and this casemust not be processed.
Output
For each test case in the inputfile output a line containing the representation of the given fraction in the Stern-Brocot number system.
Sample Input
5 7878 323
1 1
Sample Output
LRRLRRLRRLRLLLLRLRRR
#include <stdio.h>
struct {int x;int y;}tree[10];
int main(void)
{
int a,b;
while(scanf("%d%d",&a,&b)==2){
if(a==1&&b==1) break;
tree[0].x=0,tree[0].y=1;
tree[1].x=1,tree[1].y=1;
tree[2].x=1,tree[2].y=0;
while(tree[1].x!=a||tree[1].y!=b){
if(a*tree[1].y>b*tree[1].x){
printf("R");
tree[0]=tree[1];
tree[1].x+=tree[2].x,tree[1].y+=tree[2].y;}
else{
printf("L");
tree[2]=tree[1];
tree[1].x+=tree[0].x,tree[1].y+=tree[0].y;}
}
printf("\n");}
return 0;
}