Python Narcissistic Number
## Python: Check if a Number is a Narcissistic Number
In number theory, a **Narcissistic number** (also known as a **pluperfect digital invariant (PPDI)**, an **Armstrong number**, or a **plus perfect number**) is a number that is the sum of its own digits each raised to the power of the number of digits.
For example, $153$ is a 3-digit narcissistic number because:
$$1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153$$
Similarly, $1634$ is a 4-digit narcissistic number because:
$$1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634$$
This tutorial demonstrates how to implement a clean, efficient Python program to check whether a given integer is a Narcissistic number.
---
## Implementation Approach
To determine if a number is narcissistic, we can follow these steps:
1. Convert the integer to a string to easily access each individual digit and determine the total number of digits ($n$).
2. Iterate through each digit, convert it back to an integer, and raise it to the power of $n$.
3. Sum these powered values.
4. Compare the final sum with the original number. If they are equal, the number is narcissistic.
---
## Code Example
Below is the standard Python implementation using a helper function:
```python
def is_narcissistic_number(num):
# Convert the number to a string to process digit by digit
num_str = str(num)
# Get the total number of digits (n)
n = len(num_str)
# Calculate the sum of each digit raised to the power of n
sum_of_powers = sum(int(digit) ** n for digit in num_str)
# Return True if the sum equals the original number, otherwise False
return sum_of_powers == num
# --- Test the function ---
number = 153
if is_narcissistic_number(number):
print(f"{number} is a Narcissistic number.")
else:
print(f"{number} is not a Narcissistic number.")
```
### Output
```text
153 is a Narcissistic number.
```
---
## Code Explanation
1. **`is_narcissistic_number(num)`**: This function accepts an integer `num` as its parameter.
2. **`num_str = str(num)`**: Converts the integer to a string representation. This allows us to easily iterate over each digit and use Python's built-in sequence operations.
3. **`n = len(num_str)`**: Determines the length of the string, which represents the number of digits ($n$) in the original integer.
4. **`sum_of_powers = sum(int(digit) ** n for digit in num_str)`**: Uses a generator expression to iterate through each character in the string, cast it back to an integer, raise it to the power of `n`, and sum the results using the built-in `sum()` function.
5. **`return sum_of_powers == num`**: Performs a boolean comparison. If the calculated sum matches the input number, it returns `True`; otherwise, it returns `False`.
---
## Advanced Use Case: Finding Narcissistic Numbers in a Range
If you want to find all Narcissistic numbers within a specific range (for example, all 3-digit Narcissistic numbers between 100 and 999), you can use the helper function inside a loop or list comprehension:
```python
# Find all 3-digit Narcissistic numbers
narcissistic_3_digits = [x for x in range(100, 1000) if is_narcissistic_number(x)]
print("3-digit Narcissistic numbers:", narcissistic_3_digits)
```
### Output
```text
3-digit Narcissistic numbers: [153, 370, 371, 407]
```
---
## Performance Considerations
* **String Conversion vs. Mathematical Extraction**: Converting the number to a string is highly readable and idiomatic in Python. However, for extremely performance-critical applications or low-level environments, extracting digits mathematically using modulo (`%`) and floor division (`//`) operators can avoid the overhead of string allocation.
* **Time Complexity**: $\mathcal{O}(d)$ where $d$ is the number of digits in the integer. Since $d = \lfloor\log_{10}(num)\rfloor + 1$, the algorithm runs in logarithmic time relative to the value of the input number, making it highly efficient.
YouTip