Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions maths/is_armstrong_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
def is_armstrong_number(n: int) -> bool:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

"""
Check whether a non-negative integer is an Armstrong (narcissistic) number.

An Armstrong number is a number that is the sum of its own digits each raised
to the power of the number of digits in the number.

Reference:
Narcissistic number (Armstrong number) — Wikipedia
https://en.wikipedia.org/wiki/Narcissistic_number

>>> is_armstrong_number(0)
True
>>> is_armstrong_number(1)
True
>>> is_armstrong_number(153)
True
>>> is_armstrong_number(370)
True
>>> is_armstrong_number(9474)
True
>>> is_armstrong_number(9475)
False
>>> is_armstrong_number(-1) # negative numbers are not considered Armstrong
False
"""
# Only non-negative integers are considered
if n < 0:
return False

# Convert to string to count digits
digits = str(n)
power = len(digits)

# Sum of each digit raised to the 'power'
total = sum(int(d) ** power for d in digits)

return total == n