Skip to main content

How to check if a number is a narcissistic number in Python

How to check if a number is a narcissistic number in Python.

Here's a step-by-step tutorial on how to check if a number is a narcissistic number in Python.

Step 1: Understand what a narcissistic number is

A narcissistic 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 narcissistic number because 1^3 + 5^3 + 3^3 = 153.

Step 2: Write a function to check if a number is a narcissistic number

Let's start by writing a function that takes a number as input and returns True if it is a narcissistic number, and False otherwise.

def is_narcissistic_number(number):
# Convert the number to a string to calculate the number of digits
number_str = str(number)
num_digits = len(number_str)

# Initialize the sum
total = 0

# Iterate over each digit in the number
for digit in number_str:
# Convert the digit back to an integer
digit_int = int(digit)

# Add the digit raised to the power of the number of digits to the total
total += digit_int ** num_digits

# Check if the total is equal to the original number
if total == number:
return True
else:
return False

Step 3: Test the function

Now that we have our is_narcissistic_number function, let's test it with some examples:

print(is_narcissistic_number(153))  # True
print(is_narcissistic_number(370)) # True
print(is_narcissistic_number(9474)) # True
print(is_narcissistic_number(123)) # False

Step 4: Optional - Check a range of numbers

If you want to check a range of numbers to find all narcissistic numbers within that range, you can modify the function to accept a range of numbers as input instead of a single number. Here's an example:

def find_narcissistic_numbers(start, end):
narcissistic_numbers = []

for number in range(start, end+1):
if is_narcissistic_number(number):
narcissistic_numbers.append(number)

return narcissistic_numbers

print(find_narcissistic_numbers(100, 1000)) # [153, 370, 371, 407]

In this example, we call the find_narcissistic_numbers function with a range from 100 to 1000. The function will return a list of narcissistic numbers within that range.

That's it! You now have a step-by-step tutorial on how to check if a number is a narcissistic number in Python.