How To Find Factorial Of Number in JavaScript Example


Share:
Published By: Admin, Published On: Oct 22, 2021, Category: Javascript


Hello Friends,

Now let's see example of how to find factorial of number example. We will use how to find factorial of number in javascript. Here you will learn how to use javascript find factorial of number. This is a short guide on find factorial of number. Let's get started with how to find factorial of number in javascript.

Here i will give you many example how you can find factorial javascript.

Example : 1
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>How To Find Factorial Of Number in JavaScript Example - MyWebtuts.com</title>
    </head>
    <body>
        <h3>How To Find Factorial Of Number in JavaScript Example - MyWebtuts.com</h3>
        <script type="text/javascript">
            const num = parseInt(prompt('Enter a positive integer: '));

            if (num < 0) {
                console.log('Error! Factorial for negative number does not exist.');
            }
            else if (num === 0) {
                console.log(`The factorial of ${num} is 1.`);
            }
            else {
                let fact = 1;
                for (i = 1; i <= num; i++) {
                    fact *= i;
                }
                document.write(`Output: The factorial of ${num} is ${fact}.`);
            }
        </script>
    </body>
</html>
Output :
Enter a positive integer:
The factorial of 7 is 5040.
Example : 2
<!DOCTYPE html>
<html>
		<head>
				<meta charset="utf-8">
				<title>How To Find Factorial Of Number in JavaScript Example - MyWebtuts.com</title>
		</head>
		<body>
				<h3>How To Find Factorial Of Number in JavaScript Example - MyWebtuts.com</h3>
				
				<script type="text/javascript">
						function factorial(recur){
								let ans = 1;
								if (recur == 0 || recur == 1){
										return ans;
								}else{
										for(var i = recur; i >= 1; i--){
												ans = ans * i;
										}
										return ans;
								}
						}
						let recur = 5;
						ans = factorial(recur)

						document.write("Outpt : The factorial of " + recur + " is " + ans);
				</script>
		</body>
</html>
Output :
The factorial of 5 is 120

It will help you...

Share: