Ruby Program to Check Armstrong Number
sum == number after computing sum = digits.map { |d| d**digits.size }.sum.Examples
How to Think About It
Algorithm
Code
puts 'Enter a number:' number = gets.to_i digits = number.to_s.chars.map(&:to_i) power = digits.size sum = digits.map { |d| d**power }.sum if sum == number puts "#{number} is an Armstrong number" else puts "#{number} is not an Armstrong number" end
Dry Run
Let's trace the number 153 through the code
Input number
number = 153
Convert to digits
digits = [1, 5, 3]
Count digits
power = 3
Calculate sum of powers
sum = 1**3 + 5**3 + 3**3 = 1 + 125 + 27 = 153
Compare sum and number
sum == number → 153 == 153 → true
Output result
"153 is an Armstrong number"
| Digit | Digit^Power |
|---|---|
| 1 | 1 |
| 5 | 125 |
| 3 | 27 |
Why This Works
Step 1: Extract digits
We convert the number to a string and then to an array of digits to handle each digit separately.
Step 2: Calculate power
The power is the count of digits because Armstrong numbers use the number of digits as the exponent.
Step 3: Sum of powered digits
Each digit is raised to the power and summed to check if it matches the original number.
Step 4: Comparison
If the sum equals the original number, it confirms the number is an Armstrong number.
Alternative Approaches
puts 'Enter a number:' number = gets.to_i digits = number.to_s.chars.map(&:to_i) power = digits.size sum = 0 digits.each { |d| sum += d**power } if sum == number puts "#{number} is an Armstrong number" else puts "#{number} is not an Armstrong number" end
def armstrong?(number) digits = number.to_s.chars.map(&:to_i) power = digits.size digits.map { |d| d**power }.sum == number end puts 'Enter a number:' num = gets.to_i puts armstrong?(num) ? "#{num} is an Armstrong number" : "#{num} is not an Armstrong number"
Complexity: O(n) time, O(n) space
Time Complexity
The program processes each digit once to compute the power and sum, so time grows linearly with the number of digits.
Space Complexity
Extra space is used to store the digits array, which grows linearly with the number of digits.
Which Approach is Fastest?
Using map and sum is concise and efficient; using a loop is slightly more verbose but similar in performance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| map and sum | O(n) | O(n) | Concise and readable code |
| loop with accumulator | O(n) | O(n) | Explicit control over summing |
| function encapsulation | O(n) | O(n) | Reusable and clean structure |