+ 3

Whats wrong in my code to factoriel a number(n!)???

<body> <input type="number" id="factor" /> <p id="message">message</p> <button onclick="solve()">solve</button> </body> <script> function solve() { var number = document.getElementById("factor"); for (var i = 1; i <= number.value;) { console.log(i); console.log(number.value); i++; var answer = (number.value *= i); document.getElementById("message").innerHTML = answer; } } </script>

3rd Oct 2020, 2:55 PM
Keyvan
Keyvan - avatar
7 Réponses
+ 5
The problem with your code is that you are using number.value as a limit in the for loop which is okay but you are also increasing number.value with every iteration of the loop. (number.value *= i) equates to number.value = number.value * i; https://code.sololearn.com/Wh1jJ72YQmTF/#html As suggested by Kelvin Paul you need another variable to keep track of the factorial total. https://code.sololearn.com/WWIEcIID4z4v/#html Also, the location of i++ should be at the end of the code block or in the for loop statement.
3rd Oct 2020, 5:36 PM
ODLNT
ODLNT - avatar
+ 3
You can see here how it can be done with a recursive algorithm: https://code.sololearn.com/cd853UUOeh4M/?ref=app
3rd Oct 2020, 4:09 PM
JaScript
JaScript - avatar
+ 3
Bravooo
3rd Oct 2020, 7:09 PM
Keyvan
Keyvan - avatar
+ 2
function solve() { var number = Number(document.getElementById("factor").value); var fact=1; for (var i = 1; i <= number;fact*=i++); document.getElementById("message").innerHTML = fact; }
3rd Oct 2020, 3:21 PM
Kelvin Paul
Kelvin Paul - avatar
+ 2
👏👏👏👏👏👏👏
3rd Oct 2020, 7:10 PM
Keyvan
Keyvan - avatar
+ 1
ODLNT Wow nice explanation bro 👏👏😯
3rd Oct 2020, 5:39 PM
Kelvin Paul
Kelvin Paul - avatar
0
Guys can you test my game?? give your idea too. https://code.sololearn.com/W5mb619nY21W/?ref=app
3rd Oct 2020, 7:17 PM
Keyvan
Keyvan - avatar