How to write a recursive function for this expression:

p = a 0 + x (a 1 + x (a 2 + x (a 3 + ... + x (a n ))))

  • the relationship between а unknown? - vp_arth
  • these are elements of an array (any) - Dmitriy Romanov
  • x = i => i==n ? 0 : a[i] + x(i-1); x(0) x = i => i==n ? 0 : a[i] + x(i-1); x(0) - vp_arth
  • 3
    Is this your function call x() or multiplication by the variable x ? otherwise we have different opinions here :) - Harry

2 answers 2

For example :

 #include <iostream> #include <iomanip> using namespace std; const int N = 5; double A[N] = { 1, 2, 3, 4, 5 }; double calc(double x, double* a, int n = 0) { if (n == N-1) return a[n]; return calc(x,a,n+1)*x+a[n]; } double series(double x, double* a) { double sum = 0.0; for(int i = N-1; i >= 0; --i) sum = sum*x + a[i]; return sum; } int main(int argc, const char * argv[]) { for(double x = 0.0; x < 5.0; x += 0.5) { cout << setw(8) << calc(x,A) << " " << setw(8) << series(x,A) << endl; } } 

series - forehead calculation, for comparison ...

  • hmm, but it seemed to me that x is the name of the function)) - vp_arth
  • And to me - what is this Horner's scheme ... - Harry

Not sure what will be compiled. But I think something like that will look like.

 int sum(int n[], int i) { if (i == 0) { return 0; } return n[i] + sum(n, i--); }