JavaScript to check Strong Number!

Hello students and self-learners, here is another interesting JavaScript program for you to learn the fundamentals.

In this post, I am going to write a JavaScript program to check if the entered number is a Strong number or not.

What is a Strong number?
A strong number is a number if the factorial of its digit is equal to the number itself.

Eg: 145 is a strong number. Factorial of 145 is 1! + 4! + 5! = 1 + 24 + 120 = 145

So let’s write the JavaScript:

<!DOCTYPE html>
<html>
	<head>
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1"> 
	<title>JavaScript to check Strong number or not!</title>
	<script>
		function is_strong_number(){
		
			var num = document.getElementById('num').value;
			sum = 0;
			r = 0;
			
			//store the entered number in a temp variable
			temp=num;
			
			//split the number and find factorial
			while(num){
				
				i=1;
				fact=1;
				
				//get one digit from
				r=num%10;
				
				//factorial script
				while(i<=r){
					fact=fact*i;
					i++;
				}
				
				//sum the factorial value
				sum=sum+fact;
				//split the next number 
				num=Math.floor(num/10);
			}
			
			//check the sum value and stored temp value
			//if same then it's a strong number or not
			if(temp == sum){
				document.getElementById('result').innerHTML = "<b>Result:</b> Strong Number";
			}else{
				document.getElementById('result').innerHTML = "<b>Result:</b> Not a Strong Number";
			}
		}
	
	</script>
	</head>
	<body>
		<div class="container">
			<div class="row">
				<h2>JavaScript to check Strong number or not!</h2>
				<hr />
				<div class="form-group">
					<div class="form-group">
						<label for="num">Number:</label> 
						<input type="text" class="form-control" id="num" required>
					</div>
					<button type="submit" name="submit" onclick="is_strong_number()" class="btn btn-default">Submit</button>
				</div>
				<div id="result"></div>
			</div>
		</div>
	</body>
</html>

Just read the inline comments in the above script to understand it.

You can check the live demo here:

demo

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top