How to write a recursive function for this expression:
p = a 0 + x (a 1 + x (a 2 + x (a 3 + ... + x (a n ))))
How to write a recursive function for this expression:
p = a 0 + x (a 1 + x (a 2 + x (a 3 + ... + x (a n ))))
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 ...
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--); } Source: https://ru.stackoverflow.com/questions/631308/
All Articles
аunknown? - vp_arthx = i => i==n ? 0 : a[i] + x(i-1); x(0)x = i => i==n ? 0 : a[i] + x(i-1); x(0)- vp_arthx()or multiplication by the variablex? otherwise we have different opinions here :) - Harry