I want to calculate factorial of a number and show the result to the user.
There is on text field on HTML form. User is entering the number into it whose factorial is to be calculated.
I've written a program for the same and it's working absolutely fine.
But I want to also print the dynamically generated multiplication operation string during factorial calculation.
For example, If user enters 5 in the text field then the output should be like below in a separate text field on a HTML form
5*4*3*2*1=120
and not only simply 120
Following is the code I tried :
<!DOCTYPE HTML>
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function fact(num)
{
if(num==0)
return 1;
return num* fact(num-1);
}
</script>
</head>
<body>
<form name="f1">
Enter the Number :<input type="text" length="8" name="txt1"><br>
<input type="button" value="Find factiorial" onclick="this.value=fact(parseInt(txt1.value, 10))">
</form>
</body>
</html>
This is easier if you take a regular loop instead:
function fact(num){
let calc = "" + num, res = num;
while(--num > 0){
res *= num;
calc += " * " + num;
}
return calc + " = " + res;
}
Or if you really want recursion you could pass a touple type:
function fact(n, res = 1, calc = ""){
res *= n;
calc += (calc ? " * ":"") + n;
if(n <= 1)
return [res, calc + " = " + res];
return fact(n - 1, res, calc);
}