PHP Program to Check Armstrong Number
if ($sum == $number) { echo 'Armstrong'; }.Examples
How to Think About It
Algorithm
Code
<?php $number = 153; $sum = 0; $digits = strlen((string)$number); $temp = $number; while ($temp > 0) { $digit = $temp % 10; $sum += pow($digit, $digits); $temp = (int)($temp / 10); } if ($sum == $number) { echo "$number is an Armstrong number"; } else { echo "$number is not an Armstrong number"; } ?>
Dry Run
Let's trace 153 through the code
Initialize variables
number=153, sum=0, digits=3, temp=153
First loop iteration
digit=153 % 10 = 3; sum=0 + 3^3=27; temp=153 / 10=15
Second loop iteration
digit=15 % 10 = 5; sum=27 + 5^3=27 + 125=152; temp=15 / 10=1
Third loop iteration
digit=1 % 10 = 1; sum=152 + 1^3=152 + 1=153; temp=1 / 10=0
Compare sum and number
sum=153, number=153; they are equal
| Iteration | Digit | Sum after power | Temp after division |
|---|---|---|---|
| 1 | 3 | 27 | 15 |
| 2 | 5 | 152 | 1 |
| 3 | 1 | 153 | 0 |
Why This Works
Step 1: Count digits
We use strlen to find how many digits the number has, which is needed to raise each digit to the correct power.
Step 2: Sum powers of digits
Each digit is extracted using modulus and raised to the power of the digit count using pow, then added to the sum.
Step 3: Compare sum to original
If the sum equals the original number, it confirms the number is Armstrong, otherwise it is not.
Alternative Approaches
<?php $number = 9474; $digits = strlen((string)$number); $sum = 0; foreach (str_split($number) as $digit) { $sum += pow($digit, $digits); } if ($sum == $number) { echo "$number is an Armstrong number"; } else { echo "$number is not an Armstrong number"; } ?>
<?php function armstrongSum($num, $digits) { if ($num == 0) return 0; $digit = $num % 10; return pow($digit, $digits) + armstrongSum((int)($num / 10), $digits); } $number = 153; $digits = strlen((string)$number); $sum = armstrongSum($number, $digits); if ($sum == $number) { echo "$number is an Armstrong number"; } else { echo "$number is not an Armstrong number"; } ?>
Complexity: O(d) time, O(1) space
Time Complexity
The program loops through each digit once, so time grows linearly with the number of digits, O(d).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is constant, O(1).
Which Approach is Fastest?
The iterative method using modulus and division is fastest and uses least memory compared to string or recursive methods.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative modulus | O(d) | O(1) | Fastest and memory efficient |
| String manipulation | O(d) | O(d) | Easier to read, good for beginners |
| Recursive | O(d) | O(d) | Elegant but uses more memory |
strlen on the number converted to string to get digit count easily.