2021-05-15 07:40:22 +02:00
|
|
|
# A ruby program to determine whether a given number is an Armstrong number
|
2021-05-07 16:44:06 +02:00
|
|
|
# Wiki url: https://en.wikipedia.org/wiki/Narcissistic_number
|
|
|
|
# other resources: https://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/arms.html
|
|
|
|
|
|
|
|
#
|
|
|
|
# Examples: -> 153 = (1 * 1 * 1) + (5 * 5 * 5) + (3 * 3 * 3) [Armstrong number] and -> 125 != (1 * 1 * 1) + (2 * 2 * 2) + (5 * 5 * 5)
|
|
|
|
# -> 1634 = (1 * 1 * 1 * 1) + (6 * 6 * 6 * 6) + (3 * 3 * 3 * 3) + (4 * 4 * 4 * 4)
|
|
|
|
#
|
|
|
|
|
|
|
|
def armstrong_number(number)
|
|
|
|
num = number
|
|
|
|
sum = 0
|
|
|
|
len = number.digits.count
|
2021-09-03 22:24:58 +02:00
|
|
|
while number != 0
|
2021-05-07 16:44:06 +02:00
|
|
|
remainder = number % 10
|
2021-09-03 22:24:58 +02:00
|
|
|
sum += remainder**len
|
2021-05-07 16:44:06 +02:00
|
|
|
number /= 10
|
|
|
|
end
|
|
|
|
|
|
|
|
if num == sum
|
|
|
|
"The number #{num} is an Armstrong number."
|
|
|
|
else
|
|
|
|
"The number #{num} is not an Armstrong number."
|
|
|
|
end
|
2021-09-03 22:24:58 +02:00
|
|
|
rescue StandardError
|
|
|
|
'Error: Please provide number only!'
|
2021-05-07 16:44:06 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
#
|
|
|
|
# Valid inputs
|
|
|
|
#
|
|
|
|
puts armstrong_number(153)
|
|
|
|
# The number 153 is an Armstrong number.
|
|
|
|
|
|
|
|
puts armstrong_number(0)
|
|
|
|
# The number 0 is an Armstrong number.
|
|
|
|
|
|
|
|
puts armstrong_number(370)
|
|
|
|
# The number 370 is an Armstrong number.
|
|
|
|
|
|
|
|
puts armstrong_number(10)
|
|
|
|
# The number 10 is not an Armstrong number.
|
|
|
|
|
|
|
|
puts armstrong_number(1634)
|
|
|
|
# The number 1634 is an Armstrong number.
|
|
|
|
|
|
|
|
puts armstrong_number(123)
|
|
|
|
# The number 123 is not an Armstrong number.
|
|
|
|
|
|
|
|
#
|
|
|
|
# Invalid inputs
|
|
|
|
#
|
2021-09-03 22:24:58 +02:00
|
|
|
puts armstrong_number('153')
|
2021-05-07 16:44:06 +02:00
|
|
|
# Error: Please provide number only!
|
|
|
|
|
2021-09-03 22:24:58 +02:00
|
|
|
puts armstrong_number('a')
|
2021-05-07 16:44:06 +02:00
|
|
|
# Error: Please provide number only!
|