In this tutorial we are going to write a simple javascript programme which can calculate factorial of any number . First we have to know that formula how to find out factorial.
Factorial of 3 = 3 * (3-1) * (3-2) = 6
or 3! = 3*2*1=6
Formula : n! = 1×2×3×4×...×n
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Calculate Factorial</title>
</head>
<body>
<b>Factorial Calculator</b><br/>
<input type="text" id="no" placeholder="Enter an Integer "/><br/>
<input type="submit" id="submit" value="Calculate">
<p id="result"></p>
<script>
document.getElementById("submit").addEventListener("click", calculate);
function calculate(){
var n=document.getElementById("no").value;
var i;
var fact =1;
if(n==""){
alert("Enter an Integer");
}else{
while(n>0)
{
fact = fact *n;
n-=1;
}
document.getElementById("result").innerHTML = fact ;
}
}
</script>
</body>
</html>
Example Factorial Calculator