A recursive function is a function that calls itself .
But what are they for? , is not more or less efficient since it depends on the programming language and the implementation of the algorithm, then?
They make a cleaner and more elegant code.
And how is a recursive function conformed?
A recursive function conforms to a base condition, which you probably have heard, but what does it mean?
It means that obviously the function has to stop at some point, otherwise the function will be called endless times ..
And it will also be conformed by its algorithm itself.
p.e:
Factorial of a number:
Recursive v / s Cycle
Recursive:
function _f(number){
if(number === 1) return number;
return number * _f(number -1);
}
console.log(_f(5));
function _fFor (number){
var acc = 1;
while (number > 1) {
acc *= number;
number--;
}
return acc;
}
console.log(_fFor(5));
In the case of taking the factorial of a number, how does it work?
The factorial of a number works like this:
n = n * (n-1) + (n-1) * (n-2) .... 1 Hasta llegar a 1
Until you reach 1, because if you multiplied by 0, it would always give 0 (any number * 0 is = 0)
We analyze your function:
function factorial(n) { // 1° Recibe el numero al cual calculara el factorial
/* Supondremos que necesitamos el factorial de 4 */
if (n === 0) { // 3° cuando sea 0, NO multiplica por 0, osino anularia todo, sino por 1 que es el neutro multiplicativo
return 1;
} else {
// This is it! Recursion!!
return n * factorial(n - 1); // 2° Retornara 4 * 4-1 , ya que la funcion factorial en si retorna el n -1 y asi hasta llegar a 0
}
}
If you ask, because it returns n * factorial (n-1) is because it must "acumularlo"
, then, the value is accumulated internally and then in the base case, in this case when it is 0, returns the value fully accumulated.