MEEE asked in Computers & InternetSoftware · 8 years ago

Continued fractions c++, PLEASE Help?

Continued Fraction

The general form of a continued fraction is:

where a0 is an integer, all other ai are positive integers, and n is a non-negative integer. We can specify a continued fraction by an array of integers containing the values a0 … an.

1. Write a function that takes an array of integers as specified above (and ending with a -1) and returns the value of the fraction as a double.

2. Write a function that takes an array of integers as specified above (and ending with a -1). Your function will represent the value of the continued fraction as a “regular” fraction, p/q, in lowest terms. We are looking for the result of doing the fractional arithmetic and keeping everything in integers as we work our way through. The function returns a 2-element integer array, v, with v[0]=p and v[1]=q.

3. Write recursive functions that, given the above representation of a continued fraction, returns p and q such that p/q represent the value of the continued fraction as a “regular” fraction in lowest terms, as in question 2 above.

2 Answers

Relevance
  • cja
    Lv 7
    8 years ago
    Favorite Answer

    I'll help you get started by showing you how I'd do the recursive function. I prefer to have the array size as an argument, rather than using the arbitrary sentinel as described in the problem statement. For a recursive formula such as this, it's easiest to write a recursive function. The rest of the assignment seems tedious, so I'll leave that to you.

    //

    // Simple continued fraction calculation.

    //

    #include <iostream>

    #include <vector>

    #include <cmath>

    using namespace std;

    double scf(const int *, size_t);

    int a1[] = { 4,2,1,3,1,2,8,2,1,3,1,2,8 };

    size_t a1Len = sizeof(a1) / sizeof(a1[0]);

    int pi[] = { 3,7,15,1,292,1,1,1,2,1,3,1 };

    size_t piLen = sizeof(pi) / sizeof(pi[0]);

    int main(int argc, char *argv[]) {

        cout << scf(a1, a1Len) << endl;

        cout << scf(pi, piLen) << endl;

        return 0;

    }

    double scf(const int *a, size_t aLen) {

        if (aLen == 1) return *a;

        return *a + 1.0 / scf(a + 1, aLen - 1);

    }

    #if 0

    Program output:

    4.3589

    3.14159

    #endif

  • Anonymous
    8 years ago

    cool story bro

Still have questions? Get your answers by asking now.