|
1 | | -""" |
2 | | -In number theory, a narcissistic number (also known as a pluperfect digital invariant (PPDI), an Armstrong number (after Michael F. Armstrong) or a plus perfect number), |
3 | | -in a given number base b, is a number that is the total of its own digits each raised to the power of the number of digits. |
4 | | -Source: https://en.wikipedia.org/wiki/Narcissistic_number |
5 | | -NOTE: |
6 | | -this scripts only works for number in base 10 |
7 | | -""" |
| 1 | +def is_armstrong_number(number: str) -> bool: |
| 2 | + """Check if a number (as a string) is a narcissistic/Armstrong number.""" |
| 3 | + # Logic: Get the exponent (number of digits) |
| 4 | + exponent = len(number) |
| 5 | + |
| 6 | + # Logic: Sum each digit raised to the power in a single line |
| 7 | + # This uses a generator, which is memory efficient. |
| 8 | + total = sum(int(digit) ** exponent for digit in number) |
| 9 | + |
| 10 | + # Return the boolean result instead of printing |
| 11 | + return total == int(number) |
8 | 12 |
|
| 13 | +# --- Main execution --- |
| 14 | +user_input = input("Enter the number: ") |
9 | 15 |
|
10 | | -def is_armstrong_number(number: str): |
11 | | - total: int = 0 |
12 | | - exp: int = len( |
13 | | - number |
14 | | - ) # get the number of digits, this will determinate the exponent |
15 | | - |
16 | | - digits: list[int] = [] |
17 | | - for digit in number: |
18 | | - digits.append(int(digit)) # get the single digits |
19 | | - for x in digits: |
20 | | - total += x**exp # get the power of each digit and sum it to the total |
21 | | - |
22 | | - # display the result |
23 | | - if int(number) == total: |
24 | | - print(number, "is an Armstrong number") |
25 | | - else: |
26 | | - print(number, "is not an Armstrong number") |
27 | | - |
28 | | - |
29 | | -number = input("Enter the number : ") |
30 | | -is_armstrong_number(number) |
| 16 | +if is_armstrong_number(user_input): |
| 17 | + print(f"{user_input} is an Armstrong number") |
| 18 | +else: |
| 19 | + print(f"{user_input} is not an Armstrong number") |
0 commit comments