Skip to content

Commit c710f38

Browse files
authored
Add is_armstrong_number function
Implement function to check Armstrong numbers with examples.
1 parent c79034c commit c710f38

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

maths/is_armstrong_number.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
def is_armstrong_number(n: int) -> bool:
2+
"""
3+
Check whether a non-negative integer is an Armstrong (narcissistic) number.
4+
5+
An Armstrong number is a number that is the sum of its own digits each raised
6+
to the power of the number of digits in the number.
7+
8+
Reference:
9+
Narcissistic number (Armstrong number) — Wikipedia
10+
https://en.wikipedia.org/wiki/Narcissistic_number
11+
12+
>>> is_armstrong_number(0)
13+
True
14+
>>> is_armstrong_number(1)
15+
True
16+
>>> is_armstrong_number(153)
17+
True
18+
>>> is_armstrong_number(370)
19+
True
20+
>>> is_armstrong_number(9474)
21+
True
22+
>>> is_armstrong_number(9475)
23+
False
24+
>>> is_armstrong_number(-1) # negative numbers are not considered Armstrong
25+
False
26+
"""
27+
# Only non-negative integers are considered
28+
if n < 0:
29+
return False
30+
31+
# Convert to string to count digits
32+
digits = str(n)
33+
power = len(digits)
34+
35+
# Sum of each digit raised to the 'power'
36+
total = sum(int(d) ** power for d in digits)
37+
38+
return total == n

0 commit comments

Comments
 (0)