Last active
March 25, 2021 17:45
-
-
Save JuanSeBestia/a34fec0ffe3109bef7bac6364e8f2731 to your computer and use it in GitHub Desktop.
recursion-examples.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Funcion que imprime n veces Dani cumple i | |
* Dani cumple 1 | |
* Dani cumple 2 | |
* Dani cumple 3 | |
* ... | |
* Dani cumple 30 | |
*/ | |
function cantar(edad) { | |
let valorActual = 1; | |
while (valorActual <= edad) { | |
console.log("Dani cumple " + valorActual); | |
valorActual++; | |
} | |
} | |
// cantar(30) | |
function empezarACantarRecursivo(edad) { | |
cantarRecursivo(edad, 1); | |
} | |
function cantarRecursivo(edad, valorActual = 1) { | |
if (valorActual <= edad) { | |
console.log("Dani cumple " + valorActual); | |
valorActual++; | |
cantarRecursivo(edad, valorActual + 1); | |
} | |
} | |
// empezarACantarRecursivo(30); | |
// cantarRecursivo(40); | |
/** | |
* 7! = | |
* ==> 7 * 6 = 42 | |
* ==> 42 * 5 = 210 | |
* ==> 210 * 4 = 840 | |
* ==> 840 * 3 = 2520 | |
* ==> 2520 * 2 = 5040 | |
* ==> 5040 * 1 = 5040 | |
* @param {*} numeroN | |
*/ | |
function factorial(numeroN) { | |
let acc = 1; | |
let valorActual = numeroN; | |
while (valorActual >= 1) { | |
acc = acc * valorActual; | |
console.log(acc); | |
valorActual--; | |
} | |
} | |
// factorial(7); | |
/** | |
* 7! = | |
* ==> 7 * 6 = 42 | |
* ==> 42 * 5 = 210 | |
* ==> 210 * 4 = 840 | |
* ==> 840 * 3 = 2520 | |
* ==> 2520 * 2 = 5040 | |
* ==> 5040 * 1 = 5040 | |
* @param {*} numeroN | |
*/ | |
function factorialRecursivo(numeroN, acc = 1, valorActual = numeroN) { | |
if (valorActual >= 1) { | |
acc = acc * valorActual; | |
console.log(acc); | |
const resultado = factorialRecursivo(numeroN, acc, valorActual - 1); | |
return resultado; | |
} else { | |
return acc; | |
} | |
} | |
// console.log("resultado es ", factorialRecursivo(7)); | |
/** | |
* n! =1 * 2 * 3 * 4 * ... * (n-1) * n | |
* n! = (n-1)! * n | |
* @param {*} numeroN | |
*/ | |
function factorialRecursivoMatematico(numeroN) { | |
if (numeroN < 2) { | |
return 1; | |
} else { | |
return factorialRecursivoMatematico(numeroN - 1) * numeroN; | |
} | |
} | |
console.log("resultado es ", factorialRecursivoMatematico(7)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment