Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horner's Rule C/C++ Using Recursion

Tags:

c++

recursion

I learned about Horner's Rule here for the first time: Horner's rule in C++ Since I am learning about recursion ATM, I was wondering if it is possible to implement this algorithm using recursion ?

int HornerR( int a[], int n, int x, int index )
{
    if (index==n) return a[n];
    else  
        return x*HornerR(a,n ,x,index+1) + a[index];
} 

I think it's only possible with a fourth parameter.

like image 309
user1290709 Avatar asked Mar 08 '26 11:03

user1290709


1 Answers

You can do it with pointer arithmetic:

  1. Base Case at the end of array (check n) return constant parameter
  2. Recursive Case return current cell added to variable multiplied recursive call
  3. Recursive Call move the array to next cell and update the counter (n)

Basically this lets you calculate the index variable by moving the array to the next position and sending that (and always using the first cell) instead of sending the whole array every time

like image 187
twain249 Avatar answered Mar 10 '26 04:03

twain249