PowerShell Script to Check Armstrong Number
$sum = 0; $digits = $num.ToString().ToCharArray(); foreach ($d in $digits) { $sum += [math]::Pow([int]$d, $digits.Length) }; if ($sum -eq $num) { 'Armstrong' } else { 'Not Armstrong' }.Examples
How to Think About It
Algorithm
Code
$num = Read-Host 'Enter a number' $digits = $num.ToString().ToCharArray() $power = $digits.Length $sum = 0 foreach ($d in $digits) { $sum += [math]::Pow([int]$d, $power) } if ($sum -eq [int]$num) { Write-Output "$num is an Armstrong number." } else { Write-Output "$num is not an Armstrong number." }
Dry Run
Let's trace the number 153 through the code
Split digits
Digits = ['1', '5', '3'], Power = 3
Calculate sum
Sum = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
Compare sum
Sum 153 equals original number 153, so it is Armstrong
| Digit | Digit^Power | Running Sum |
|---|---|---|
| 1 | 1 | 1 |
| 5 | 125 | 126 |
| 3 | 27 | 153 |
Why This Works
Step 1: Split number into digits
We convert the number to a string and split it so we can work with each digit separately using ToCharArray().
Step 2: Calculate power sum
Each digit is raised to the power of the total number of digits using [math]::Pow() and added to a sum.
Step 3: Compare sum to original
If the sum equals the original number, it confirms the number is Armstrong.
Alternative Approaches
$num = Read-Host 'Enter a number' $digits = $num.ToString().ToCharArray() | ForEach-Object { [int]$_ } $power = $digits.Length $sum = ($digits | ForEach-Object { [math]::Pow($_, $power) }) | Measure-Object -Sum | Select-Object -ExpandProperty Sum if ($sum -eq [int]$num) { Write-Output "$num is an Armstrong number." } else { Write-Output "$num is not an Armstrong number." }
function Is-Armstrong($num) { $digits = $num.ToString().ToCharArray() $power = $digits.Length $sum = 0 foreach ($d in $digits) { $sum += [math]::Pow([int]$d, $power) } return $sum -eq $num } $num = Read-Host 'Enter a number' if (Is-Armstrong([int]$num)) { Write-Output "$num is an Armstrong number." } else { Write-Output "$num is not an Armstrong number." }
Complexity: O(n) time, O(n) space
Time Complexity
The script loops through each digit once, so time grows linearly with the number of digits, O(n).
Space Complexity
It stores digits in an array, so space also grows linearly with digit count, O(n).
Which Approach is Fastest?
All approaches have similar time and space complexity; using pipelines may be slightly slower but more readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Basic loop | O(n) | O(n) | Simplicity and clarity |
| Pipeline with Measure-Object | O(n) | O(n) | PowerShell idiomatic style |
| Function encapsulation | O(n) | O(n) | Code reuse and modularity |