Q:

Armstrong Number in Php

belongs to collection: PHP Programs

0

An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.

0, 1, 153, 371, 407, 471, etc are Armstrong numbers.

For example,

 

407 = (4*4*4) + (0*0*0) + (7*7*7)  

        = 64 + 0 + 343  

407 = 407  

Logic:

  • Take the number.
  • Store it in a variable.
  • Take a variable for sum.
  • Divide the number with 10 until quotient is 0.
  • Cube the remainder.
  • Compare sum variable and number variable.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Armstrong number in PHP

Below program checks whether 407 is Armstrong or not.

Example:

<?php  
$num=407;  
$total=0;  
$x=$num;  
while($x!=0)  
{  
$rem=$x%10;  
$total=$total+$rem*$rem*$rem;  
$x=$x/10;  
}  
if($num==$total)  
{  
echo "Yes it is an Armstrong number";  
}  
else  
{  
echo "No it is not an armstrong number";  
}  
?>  

Output:

Look at the above snapshot, the output displays that 407 is an Armstrong number.


Armstrong number using Form in PHP

A number is Armstrong or can also be checked using a form.

Example:

<html>  
<body>  
 <form method="post">  
 Enter the Number:  
   <input type="number" name="number">  
   <input type="submit" value="Submit">  
  </form>  
</body>  
</html>  
<?php  
 if($_POST)  
 {   
  //get the number entered  
  $number = $_POST['number'];  
  //store entered number in a variable  
  $a = $number;  
  $sum  = 0;  
  //run loop till the quotient is 0  
  while( $a != 0 )  
  {  
   $rem   = $a % 10; //find reminder  
   $sum   = $sum + ( $rem * $rem * $rem ); //cube the reminder and add it to the sum variable till the loop ends  
   $a   = $a / 10; //find quotient. if 0 then loop again  
  }  
  //if the entered number and $sum value matches then it is an armstrong number  
  if( $number == $sum )  
  {  
   echo "Yes $number an Armstrong Number";  
  }else  
  {  
   echo "$number is not an Armstrong Number";  
  }  
 }  
?>     

Output:

On entering the number 371, we got the following output.

On entering the number 9999, we got the following output.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Palindrome Number in Php... >>
<< Factorial Program in Php...