Checking Strong number in PHP

A number is called strong number if the number is equal to the sum of factorials of digits of the number.

Example :
Number 145 is a strong number as sum of factorial of 1 , 4 and 5 is equal to 145
145= 1! + 4! + 5!

Checking Strong number and generating all strong numbers within a range in PHP

There are three parts in this script.
  1. Function to get Factorial of a number
  2. Collecting all digits of the number
  3. Finding sum of the factorial of digits and comparing

Function to get Factorial of a number

We will use one function to get the factorial of any input number.
function fact($n){
$factorial=1;
for ($i=1; $i<=$n;$i++){
	$factorial=$factorial*$i;
}
return $factorial;
}
Getting all digits of the input number.
$n1=1234; // Sample number  
while($n1>0){
	$d=$n1%10; // reminder of division 
	echo $d; // one digit from right
	$n1=floor($n1/10); // floor value
}
Using the above two concepts we can find out the sum of factorial of any number. We will create one sticky form to take user input and then find out it is strong number or not.
<?Php
$n1=$_POST['n1'];
echo "<form method=POST action=''>
<input type=text name=n1 value='$n1'> 
<input type=submit value=Submit>
</form>";
function fact($n){
$factorial=1;
for ($i=1; $i<=$n;$i++){
	$factorial=$factorial*$i;
}
return $factorial;
}
$sum=0;
$n2=$n1;
while($n1>0){
	$d=$n1%10; // reminder of division 
	$sum = $sum  + fact($d);
	$n1=floor($n1/10); // floor value
}
if($n2==$sum){
	
echo "$n2 is  a Strong Number ";	
}else{
echo "$n2 is NOT a Strong Number ";		
}
?>

Listing all strong numbers

Without taking user input we can list all strong number over a range. We can find out all strong numbers less than 100000.
<?Php
function fact($n){
$factorial=1;
for ($i=1; $i<=$n;$i++){
	$factorial=$factorial*$i;
}
return $factorial;
}
for($i=10;$i<100000;$i++){
$sum=0;
$n2=$n1=$i;
while($n1>0){
	$d=$n1%10; // reminder of division 
	$sum = $sum  + fact($d);
	$n1=floor($n1/10); // floor value
}
if($n2==$sum){
echo "$n2 is  a Strong Number <br> ";	
}

}
?>
Output
145 is a Strong Number
40585 is a Strong Number
Introduction to PHP Factorial of a number Sum of Digits of a number
Armstrong number Fibonacci Series
Basic Codes Check the string or number is Palindrome or not in PHP
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer