Find Armstrong Number in PHP with Program

This blog explains about Find Armstrong Number in PHP with Program . They are explained very well below : 

_______________________________________________________________________________

Hi,

Find Armstrong Number in PHP With Program – This is one of the interview questions usually asked. 

PHP | Check if a number is armstrong number

Given a number, we need to check whether it is an armstrong number or not in PHP. An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.

Examples:

Input  : 407
Output : Yes
407 = (4*4*4) + (0*0*0) + (7*7*7)  
    = 64 + 0 + 343  
    = 407  

Input  : 303
Output : No

In this program, we will check the sum of cube values of individual digits are equal to given  number or not.

Let us consider the number is 370.

Here 3 cube is 27 and 7 cube is 343 and 0 cube is 0.

The sum of all cube value is 370.

Aim:(3*3*3+7*7*7+0*0*0)  

First(at $i=0) we find modulus with 10(370%10) it gives result  0.

Then calculate cube value using pow() , add with $s and assign whole value into $s again.

Next we need 37 for remaining operations so that we divide again the given with 10.

Here we have used three digit number, hence we have set for loop runs at three time.

When  $i=0, $r will become 7, so $s=343. At final loop($i=2) $r=3, and $s=370. It gives same number  what  we have given.

Ok, Lets go to the program:

<?php
$m = 370; $r=0; $s=0;
for($i=0; $i<3; $i++)
{
$r=$m%10;
$s=$s+pow($r,3); // {($i=0), 0*0*0} + {($i=1), 0+ 7*7*7} + {($i=2), 343+ 3*3*3}
$m = $m/10;
}
echo $s.”<br>”;
if($s=$m)
{
echo “Given Number is an Armstrong Number”;
}
?>

OUTPUT:

370

Given Number is an Armstrong Number

________________________________________________________________________________

REFERENCES :

https://www.geeksforgeeks.org/php-check-number-armstrong-number/