Search code examples
c++algorithmformulacontinued-fractions

The sum of a sequence


I'm trying to make a function for calculating this formula

formula

#include <iostream>
#include <vector>
double Sequence(std::vector < double > & a) {
  double result = 0;
  for (int i = a.size() - 1; i > 0; i--) {
    if (a[i] == 0) throw std::domain_error("Dividing with 0");
    if (i > 1)
      result += 1 / (a[i - 1] + 1 / a[i]);
    else result += a[i - i];
    std::cout << a[i] << " " << result << " " << "\n";
  }
  return result;
}
int main() {
  std::vector<double>a{1,2,3,4,5};
  try {
    std::cout << Sequence(a);
  } catch (std::domain_error e) {
    std::cout << e.what();
  }

  return 0;
}

Code gives correct result for {1,2,3} sequence. However, if I add a few numbers to that sequence result becomes wrong. Could you help me to fix this?


Solution

  • if (i > 1)
      result += 1 / (a[i - 1] + 1 / a[i]);
    else result += a[i - i];
    

    This is wrong; it just happens to work if you have three or fewer terms.

    The recurrence you actually want is

    if (i == a.size() - 1) {
        result = a[i];
    } else {
        result = a[i] + 1 / result;
    }
    

    you can see that this is a correct recurrence by the fact that Tidying up some more things (removing the condition from inside the loop, fixing an off-by-one in the loop termination condition, and correcting the exception condition):

    double Sequence(std::vector<double> &a) {
      double result = a[a.size() - 1];
      for (int i = a.size() - 1; i >= 0; i--) {
        if (result == 0)
          throw std::domain_error("Dividing with 0");
        result = a[i] + 1 / result;
      }
      return result;
    }