A number equal to sum of the power of 3 of its digits. ( for 3 digit number )
A number equal to sum of the power of 4 of its digits. ( for 4 digit number )
A number equal to sum of the power of n of its digits. ( for n digit number )
Example 1:
153=13 + 53 + 33
153=1 + 125 + 27
So 153 is an Armstrong number
Checking Armstrong numbers or generating Armstrong numbers in a range using PHP
Three digit Armstrong number
We can use pow() to get the cube of the digit. Inside the while loop we have taken out all digits of the number and then got the sum of the pow() value of each digit of the number. At the end if this, if sum is matching with the original number then we can print saying this is an Armstrong number.
$n1=153;
$n2=$n1;
$sum=0;
while($n1>0){
$d=$n1%10; // reminder of the division
$sum=$sum + pow($d,3);
//$n1=floor($n1/10);
$n1=$n1/10;
//$n1=intdiv($n1,10); // for PHP 7 and above
}
if($sum==$n2){
echo "$n2 is an Armstrong number ";
}else{
echo "$n2 is NOT an Armstrong number ";
}
Output
153 is an Armstrong number
Armstrong numbers over a range
Armstrong number of any length can be collected by specifying a range. Here we will display all three digit, four digit and five digit Armstrong numbers. We will find out the length of the number ( in terms of number of digits ) and then use the same value to get the pow() of the digit.
for($i=10;$i<=100000;$i++){
$n2=$n1=$i;
$p=strlen($n1); // Number of digits in the number
$sum=0;
while($n1>0){
$d=$n1%10; // reminder of the division
$sum=$sum + pow($d,$p);
//$n1=floor($n1/10);
$n1=$n1/10;
//$n1=intdiv($n1,10); // for PHP 7 and above
}
if($sum==$n2){
echo "$n2 is an Armstrong number <br>";
}
}
Output is here
153 is an Armstrong number
370 is an Armstrong number
371 is an Armstrong number
407 is an Armstrong number
1634 is an Armstrong number
8208 is an Armstrong number
9474 is an Armstrong number
54748 is an Armstrong number
92727 is an Armstrong number
93084 is an Armstrong number