×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

JavaScript code to check number is Perfect or not

In this JavaScript code, we are going to check whether a given number is perfect number or not.
Submitted by Aleesha Ali, on March 28, 2018

Perfect number

A number is said to be perfect when its value is equal to its sum of complete divisors.

Example of perfect numbers are: 6, 28, 496 etc

Sample Input/Output

Input:
Number: 6

Output:
It is a perfect number
Explanation:

Divisors of 6 are: 1, 2, 3
Sum of the divisors is: 1+2+3 =6 

JavaScript code to check number is Perfect or not

<script>
	function perfectNumber()
	{
		var flag,number,remainder,addition = 0,i;
		number = Number(document.getElementById("N").value);
		flag = number;
		for(i = 0; i < number; i++)
		{
			remainder = number%i;
			if(remainder==0)
			{
				addition += i;
			}
		}
		if(addition == flag)
		{
			window.alert("-The inputed number is Perfect");
		}
		else
		{
			window.alert("-The inputed number is not Perfect");
		}
	}
</script>

Calling JavaScript function in HTML (HTML, JS Code)

<html>
	<head>
		<script>
			function perfectNumber()
			{
				var flag,number,remainder,addition = 0,i;
				number = Number(document.getElementById("N").value);
				flag = number;
				for(i = 0; i < number; i++)
				{
					remainder = number%i;
					if(remainder==0)
					{
						addition += i;
					}
				}
				if(addition == flag)
				{
					window.alert("-The inputed number is Perfect");
				}
				else
				{
					window.alert("-The inputed number is not Perfect");
				}
			}
		</script>
	</head>
	<body>
	<br>
	<h1>Whether a number is Perfect or not</h1>
	Enter The Number :<input type="text" name="n" id = "N"/>
	<hr color="cyan">
	<br>
	<center><button onClick="perfectNumber()">CHECK</button>
	</body>
</html>

Output

JavaScript code to check number is Perfect or not

JavaScript Examples »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.