This program is supposed to output the CalkinWilf tree In ot
This program is supposed to output the Calkin-Wilf tree. In other words it\'s supposed to show the fractions such as 1/1 and then next level is 1/2 and 2/1 ect
Please help with this thanks.
The code towards the bottom is similar to what i need the code to look like it just needs to be put into c++ code and I\'m having problems getting it into c++ code please help.
Please do not write it out I have a hard time reading other peoples hand writing please just type it out. thanks
write a c++ program that implements and tests the following two functions related to the Calkin-Wilf enumeration of the positive fractions:
Fraction cwfrac(int p);
//Returns the fraction in position p in the Calkin-Wilf enumeration.
int cwpos(Fraction f);
//Returns the position of the fraction f in the Calkin-Wilf enumeration.
This is the code that is similar to what I need it just needs to be in c++ code. Thanks
Define LibPub cwfrac(p)
Func
Local d,n,q,t,i,s
s := floor(log2(p))
t := 2s
n := 1
d := 1
q := p – t
For i,1,s
t := t/2
If t Ÿ q Then
n := n + d
q := q - t
Else
d := n + d
EndIf
EndFor
Return n/d
EndFunc
code for the fraction part of the assignment ^
Define LibPub cwpos(n,d)
Func
Local p,nn,dd,t
nn := n
dd := d
p := 0
t := 1
While nn/dd Á 1
If nn < dd Then
dd := dd - nn
Else
p := P + t
nn := nn - dd
EndIf
t := 2t
EndWhile
p := p + t
Return p
EndFunc
^code for the position of the fraction in the Calkin-Wilf tree
Solution
Following is the required c++ code :
#include <iostream>
#include <cmath>
using namespace std;
double Log2( double n )
{
return log( n ) / log( 2 );
}
struct fraction{
int num;
int den;
fraction( int n, int d ){
num = n; den = d;
}
};
fraction cwfrac( int p){
int d,n,q,t,i,s;
s = floor(Log2(p));
t = 2*s;
n = 1;
d = 1;
q = p-t;
for( i = 1; i <= s; i++ ){
t = t/2;
if( t <= q ){
n = n + d;
q = q - t;
}
else{
d = n + d;
}
}
return fraction(n,d);
};
int cwpos( fraction f ){
int n = f.num;
int d = f.den;
int p,nn,dd,t;
nn = n;
dd = d;
p = 0;
t = 1;
while( nn != dd ){
if(nn < dd){
dd = dd - nn;
}
else{
p = p + t;
nn = nn - dd;
}
t = 2*t;
}
p = p + t;
return p;
};
int main(){
fraction f(0,0);
for( int i = 1; i <= 5; i++ ){
cout << i << \" -> \";
f = cwfrac( i );
cout <<f.num << \"/\" <<f.den << endl;
if( i != cwpos( f )){
//error : will never come hopefully
cout << \"ERROR : \" << endl;
break;
}
};
return 0;
}


