I wrote a function in C code that calculates a polynomial value from a given array arr[] of arrsize size, where the elements are the coeffiecients.
the polynomial formula is:
$$p(x) = \sum_{i = 0}^{arrsize - 1} a_ix^i$$
With $a_i$ the polynomial coefficients. The function needs to calculate the sum $s$:
$$s = \sum_{i = 0}^{arrsize - 1} p(a_i)$$
int helper(int arr[], int arrsize, int x, int i) /*helper function that calculates the value of the polynomial*/
{
if (i==arrsize)
{return 0;}
else
{
printf("arr[%d] * %d^%d = %d\n", i, x, i, arr[i] * power_(x,i));
return arr[i]*power_(x,i) + helper(arr, arrsize, x,i+1);
}
}
int sumOfEvaluations(int arr[], int arrsize) {
if (arrsize == 0)
{return 0;}
else {
return helper(arr, arrsize, arr[arrsize-1],0) + sumOfEvaluations(arr, arrsize-1);
}
}
my problem is whenever i input an array, i don't get the result i want, for example for the array {1,2,3,4) the result should be 514, but the helper function skips part of the calculations.
i tried adding a print function before the recursive part of the function to see where it goes wrong, this is what it prints
arr[0] * 4^0 = 1
arr[1] * 4^1 = 8
arr[2] * 4^2 = 48
arr[3] * 4^3 = 256
arr[0] * 3^0 = 1
arr[1] * 3^1 = 6
arr[2] * 3^2 = 27
it starts skipping here
arr[0] * 2^0 = 1
arr[1] * 2^1 = 4
arr[0] * 1^0 = 1
From the code it seems you are trying to recursively compute the value of a polynomial:
$$p(x) = \sum_{i = 0}^{n - 1} a_i \cdot x^i$$
If this is the case then your
helperfunction will compute this value. Then you simply remove the recursive call insumOfEvaluationsgiving:Now
sumOfEvaluationscomputes the desired value.Edit: It seems I initially misunderstood the problem. You do indeed want to evaluate the polynomials with the polynomial coefficients as input. In this case the following implementation will compute the desired value:
In the case you provided the above gives $514$ as output.