Search code examples
cpathwhile-looptreefinder

C Programming - Stern-Brocot Tree path finder


I am learning the C programming language and I am having troubles with writing out the full path to the desired element in the Stern-Brocot tree. It only writes out the first number of the path. I have set it to write out 0 when taking a left, and 1 when taking a right. And whatever number I choose, it can be on the 3rd or on the 15th level, it's still writing out only the first number.

Here is the while loop:

while ((p1+p2!=p) && (q1+q2)!=q) {
    if ((p1+p2)/(q1+q2)<p/q) {
        printf("1 ");
        p1+=p2;
        q1+=q2;
    } else if (((p1+p2)/(q1+q2)>p/q)) {
        printf("0 ");
        p2+=p1;
        q2+=q1;
    }
}

Solution

  • Since you didn't show use the types you are using I'm going to assume they are integers. You are making the mistake in your if statements where the divisions are rounded to the nearest integer, and you lose the decimal places. A quick fix would be to force the code to perform floating point divisions, by casting integers to doubles.

    int p = 3 ;
    int q = 5 ;
    
    int p1 = 0 ;
    int p2 = 1 ;
    
    int q1 = 1 ;
    int q2 = 0 ;
    
    while( p1+p2 != p  && q1+q2 != q )
    {
        if (( p1+p2 )/( double )(q1+q2 ) < p/( double )q) 
        {
            printf("1 ");
            p1+=p2;
            q1+=q2;
        } 
        else if( ( p1+p2 ) / ( double )( q1+q2 ) > p/( double )q ) 
        {
            printf("0 ");
            p2+=p1;
            q2+=q1;
        }
    }
    

    Now the code correctly prints out 0 , 1 , 0. That is left, right and left to reach 3/5 in the tree.