Solution of 834 - Continued Fractions

Problem Description
source:https://uva.onlinejudge.org/external/8/834.html

Let b0, b1, b2, . . . , bn be integers with bk > 0 for k > 0. The continued fraction of order n with coeficients b1, b2, . . . , bn and the initial term b0 is defined by the following expression

which can be abbreviated as [b0; b1, . . . , bn]. An example of a continued fraction of order n = 3 is [2; 3, 1, 4]. This is equivalent to 

Write a program that determines the expansion of a given rational number as a continued fraction. To ensure uniqueness, make bn > 1. 

Input 

The input consists of an undetermined number of rational numbers. Each rational number is defined by two integers, numerator and denominator. 

Output 

For each rational number given in the input, you should output the corresponding continued fraction. 

Sample Input 

43 19 
1 2 

Sample Output 

[2;3,1,4]
[0;2] 

Solution:
#include<stdio.h>

int main()
{
    long int n, d, r, temp;
    while(scanf("%ld%ld",&n,&d)==2)
    {
        r=n/d;
        temp=n;
        n=d;
        d=temp-(d*r);
        printf("[%ld;",r);
        while(n>1)
        {
            r=n/d;
            temp=n;
            n=d;
            d=temp-(d*r);
            if(n>1)
                printf("%ld,",r);
            else
                printf("%ld",r);
        }
        printf("]\n");
    }
    return 0;
}

No comments:

Post a Comment

Write your comment - Share Knowledge and Experience