سؤال

Here's how I did it with decimals and it works:

double continuedFractionDecimal(int a[], int size)
{
    double fraction = a[size - 1];  

    for(int i = size - 2; i >= 0; i--)
    {
        fraction = a[i] + 1/fraction;
    }

    return fraction;
}

My question is how do you do the same thing with fractional arithmetic using ints: a numerator and a denominator. I need to do it nonrecursively and everything should be done within the function without including anything extra to do it. I don't think it's that hard once you know how to do it but to me it's impossible I can't visualize it, I appreciate any guidance... thank you.

هل كانت مفيدة؟

المحلول

If I understand continued fractions correctly, you don't need to compute the GCD of the numerator and the denominator.

The following program does the job:

#include <iostream>
#include <utility>

std::pair<int, int> getFraction(int a[], int size)
{
   int n = 1;
   int d = a[size-1];
   for(int i = size - 2; i >= 0; i--)
   {
      int nextd = d*a[i] + n;
      n = d;
      d = nextd;
   }

   // When we are done, d is the numerator and n is the denominator.
   return std::make_pair(d, n);
}

int main()
{
   int a[] = {4, 2, 6, 7};
   int size = sizeof(a)/sizeof(a[0]);
   std::pair<int, int> f = getFraction(a, size);
   std::cout
      << "Numerator: " << f.first
      << ", Denominator: " << f.second << std::endl;
}

Output of running the program:

Numerator: 415, Denominator: 93
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top