Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading