Skip to content
Open
Changes from all commits
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
41 changes: 41 additions & 0 deletions maths/armstrong_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from typing import Union

Check failure on line 1 in maths/armstrong_number.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F401)

maths/armstrong_number.py:1:20: F401 `typing.Union` imported but unused


def is_armstrong_number(n: int) -> bool:
"""
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
Loading