Program to find all Armstrong numbers (PHP)
An Armstrong number is an n digit number, which is equal to the sum of the nth powers of its digits. All the 1 digit numbers (1-9) are Armstrong number because 1*1=1 which is equals to number (1) itself, 2*1=2 which is equals to number(2) itself so on for all the 1 digit numbers (1-9).There are no 2 digit Armstrong numbers. Feel free to ask me if you still have doubt.
1 |
<? |
2 |
armstrong(9999); |
3 |
function armstrong($maximum_number) |
4 |
{ |
5 |
$sum=0; |
6 |
print("Armstrong numbers between 0 to $maximum_number are: "); |
7 |
|
8 |
for($i=0; $i<=$maximum_number; $i++) |
9 |
{ |
10 |
$num=$i; |
11 |
$sum=0; |
12 |
$len=strlen($i); //Length of number i.e number of digits in a number |
13 |
while($num>0) |
14 |
{ |
15 |
$rem=$num%10; |
16 |
$power=pow($rem,$len);//Raise to the power of length of each digit in a number. |
17 |
$sum=$sum+$power; //Sum of power of all digits of a number |
18 |
$num=$num/10; // Calculate next number |
19 |
} |
20 |
if($sum==$i) |
21 |
{ |
22 |
echo $i . "= Yes <br/>"; |
23 |
} |
24 |
} |
25 |
} |
26 |
?> |