You can use without recursion, because the computational time will be much smaller, below is implemented iteratively:
double quadrado(double x0, double r, int n)
{
int resultado = 0;
for(int i = 0; i<n ;i++)
{
resultado = resultado + (x0+r*i)*(x0+r*i);
}
return resultado;
}
Iterative implementation usually tends to be slightly faster in practice than recursive implementation, since a recursive implementation needs to record the current state of the processing so that it can continue where it left off after the completion of each new subordinate execution of the recursive procedure. This action consumes time and memory.
Another possible motivation for choosing an iterative algorithm rather than a recursive algorithm is that in modern programming languages the space available for the control flow is usually much smaller than the space available in the heap, and recursive algorithms tend to require more stack space than iterative algorithms.
It is important to mention that this iterative solution requires two temporary variables (relying on i) and will still spend less execution time than recursive; in general, recursive formulations of algorithms are often considered "leaner" or "more elegant" than iterative formulations.
I don’t know if I got your question right, but if the problem is the square,
x²
is the equivalent ofx*x
. If you want to keep the recursive form just replacex0 + sum_arithmetic(x0 + r, r, n-1);
forx0 * x0 + sum_arithmetic(x0 + r, r, n-1);
– Anthony Accioly
thank you very much, that was it!
– Bruno Rodrigues
@Brunorodrigues +1 for the problem, nice to see these problems involving p.a
– Pedro Rangel