Find Factorial Of A Number

Advertisements
Advertisements

The factorial is a popular mathematical concept or algorithms and very useful in computer science. In this example, we are going to accept a number as argument to JavaScript function and find the factorial of the number.

To accept the argument, we will use HTML text box control and output it in a H1 element. Learn more about HTML from our HTML tutorial.

Factorial of a Number

The factorial of a number is product of all natural numbers up to the number. Note that the factorial of 0! and 1! is 1. Suppose we are given a number 5 , then the factorial would be

5! = 1 x 2 x 3 x 4 x 5 = 120

! is the factorial notation in mathematics. So, factorial of 24 is 24! , factorial of 10 is 10!.

JavaScript Code: Find Factorial of a Number

function MyClear(){
    document.getElementById("in").value = "";
}

function Myfactorial() {

    let num = document.getElementById("in").value;
    let fact = 1;
    for(let i = 0;i <= num;i++)
     {
       if (i > 1)
       {
          fact = fact * i;
       }
       else
       {
          fact = 1;
       }
  }
    document.getElementById("out").innerHTML = fact;
}

The program use the algorithm: fact(n) = fact(n-1) * fact(n-2) repeatedly. Any of its term is product of previous two terms.

Advertisements

The full code for the program is given below. We have also added some style to the program for better display.

HTML and JavaScript Code: Find Factorial

<!DOCTYPE html>
<html>
<head>
   <title>Factorial Of a Number</title>
   <meta charset="utf-8">
   <style>
   main{
    width:20%;
	margin:auto;
   }
     #in{
	 
	  padding:10px;
	  width:150px;
	  background:whitesmoke;  
	 }
	 
	 button{
	 padding:10px;
	 margin:10px;
	 }
   </style>
</head>
<body>
<main>
<h1 id="out">Output here</h1>
<input type="text" id="in" /><br/>
<button onclick="Myfactorial()">Factorial</button>
<button onclick="MyClear()">Clear</button>
</main>
<script>
function MyClear(){

document.getElementById("in").value = "";

}

function Myfactorial() {

let num = document.getElementById("in").value;
let fact = 1;
  for(let i = 0;i <= num;i++)
  {
    
    if (i > 1)
    {
      
       fact = fact * i;
     
    }
    else{
     
     fact = 1;
    }
  }
  document.getElementById("out").innerHTML = fact;
}

</script>

</body>
</html>

Output to Browser: Find Factorial

Output - Find Factorial of a number
Output – Find Factorial of a number
Advertisements
Advertisements
Advertisements