+ 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>
7 Answers
+ 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.
+ 3
You can see here how it can be done with a recursive algorithm:
https://code.sololearn.com/cd853UUOeh4M/?ref=app
+ 3
Bravooo
+ 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;
}
+ 2
đđđđđđđ
+ 1
ODLNT Wow nice explanation bro đđđŻ
0
Guys can you test my game??
give your idea too.
https://code.sololearn.com/W5mb619nY21W/?ref=app