Is Armstrong Number
This algorithm checks whether a given number is armstrong or not. Armstrong number is a number which is equal to sum of digits raise to the power total number of digits in the number.
Some examples of armstrong numbers are:
7 = 7^1
371 = 3^3 + 7^3 + 1^3 (27 + 343 +1)
8208 = 8^4 + 2^4 +0^4 + 8^4 (4096 + 16 + 0 + 4096)
function Power($x, $y)
{
$p = 1;
for ($i = 1; $i <= $y; $i++)
{
$p *= $x;
}
return $p;
}
function IsArmstrong($num)
{
$sum = 0;
$remainder;
$digits = 0;
$temp = $num;
while ($temp != 0)
{
$digits++;
$temp = (int)($temp / 10);
}
$temp = $num;
while ($temp != 0)
{
$remainder = (int)($temp % 10);
$sum += Power($remainder, $digits);
$temp = (int)($temp / 10);
}
return $num == $sum;
}
Example
$isArmstrong = IsArmstrong(371);
Output
True