Interview challenge · easy · math, digits, loops
Armstrong Number
The challenge
An Armstrong (or narcissistic) number is equal to the sum of its digits, each raised to the power of the number of digits. Write a function that checks a number, and print all the Armstrong numbers below 1000.
Example
153 -> true (1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153)
154 -> false
9474 -> true (9^4 + 4^4 + 7^4 + 4^4)
below 1000: 1 2 3 4 5 6 7 8 9 153 370 371 407Idea: first count the digits k (in Python, the length of str(n); in C, how many times n can be divided by 10). Then take the digits one by one with % 10 and / 10, add each one raised to k, and compare the total with n. It is O(d) per number for d digits; C has no integer power, so it multiplies k times.
The solution
# Armstrong Number - ayotl.dev
def is_armstrong(n):
k = len(str(n)) # number of digits
total, m = 0, n
while m:
total += (m % 10) ** k
m //= 10
return total == n
for n in [153, 154, 9474]:
ok = is_armstrong(n)
print(n, "true" if ok else "false")
below = [n for n in range(1, 1000)
if is_armstrong(n)]
print(*below)
$ python3 armstrong_number.py
153 true
154 false
9474 true
1 2 3 4 5 6 7 8 9 153 370 371 407