Skip to content

Commit 8ba7fc5

Browse files
authored
Add Armstrong number check algorithm
Implement function to check Armstrong numbers with examples.
1 parent c79034c commit 8ba7fc5

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

maths/armstrong_number.py

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

0 commit comments

Comments
 (0)