your image

PHP Armstrong Number Program - javatpoint

javapoint
Related Topic
:- PHP Java information technology

Armstrong Number

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,

  1. 407 = (4*4*4) + (0*0*0) + (7*7*7)  
  2.         = 64 + 0 + 343  
  3. 407 = 407  

Logic:

 

13. PHP Unit testing tutorial and pages list | Automated testing with PHPUnit | CMS OOP tutorial MVC

  • 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.

Armstrong number in PHP

Below program checks whether 407 is Armstrong or not.

Example:

  1. <?php  
  2. $num=407;  
  3. $total=0;  
  4. $x=$num;  
  5. while($x!=0)  
  6. {  
  7. $rem=$x%10;  
  8. $total=$total+$rem*$rem*$rem;  
  9. $x=$x/10;  
  10. }  
  11. if($num==$total)  
  12. {  
  13. echo "Yes it is an Armstrong number";  
  14. }  
  15. else  
  16. {  
  17. echo "No it is not an armstrong number";  
  18. }  
  19. ?>  

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:

  1. <html>  
  2. <body>  
  3.  <form method="post">  
  4.  Enter the Number:  
  5.    <input type="number" name="number">  
  6.    <input type="submit" value="Submit">  
  7.   </form>  
  8. </body>  
  9. </html>  
  10. <?php  
  11.  if($_POST)  
  12.  {   
  13.   //get the number entered  
  14.   $number = $_POST['number'];  
  15.   //store entered number in a variable  
  16.   $a = $number;  
  17.   $sum  = 0;  
  18.   //run loop till the quotient is 0  
  19.   while( $a != 0 )  
  20.   {  
  21.    $rem   = $a % 10; //find reminder  
  22.    $sum   = $sum + ( $rem * $rem * $rem ); //cube the reminder and add it to the sum variable till the loop ends  
  23.    $a   = $a / 10; //find quotient. if 0 then loop again  
  24.   }  
  25.   //if the entered number and $sum value matches then it is an armstrong number  
  26.   if( $number == $sum )  
  27.   {  
  28.    echo "Yes $number an Armstrong Number";  
  29.   }else  
  30.   {  
  31.    echo "$number is not an Armstrong Number";  
  32.   }  
  33.  }  
  34. ?>     

Output:

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

 

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

Comments