Narcissistic numbers, also known as Armstrong numbers or Waterloo numbers, are fascinating entities in the realm of mathematics and programming. A narcissistic number is an n-digit number that is equal to the sum of the nth powers of its digits. For instance, 153 is a narcissistic number because 13 + 53 + 33 = 153.
Finding narcissistic numbers within a specified range can be an engaging task for Python programmers. Here’s a simple yet effective way to identify and print all narcissistic numbers in a given interval using Python.
pythonCopy Codedef is_narcissistic(num):
"""
Check if a number is narcissistic.
"""
sum = 0
n = len(str(num))
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** n
temp //= 10
return num == sum
def find_narcissistic_numbers(start, end):
"""
Find all narcissistic numbers in a given range.
"""
for num in range(start, end + 1):
if is_narcissistic(num):
print(num)
# Example usage
start = 100
end = 1000
find_narcissistic_numbers(start, end)
This script defines two functions: is_narcissistic
to check if a number is narcissistic, and find_narcissistic_numbers
to find and print all narcissistic numbers within a specified range. The is_narcissistic
function calculates the sum of the nth powers of the digits of the given number, where n is the number of digits, and checks if this sum is equal to the number itself.
The find_narcissistic_numbers
function iterates through each number in the specified range, leveraging the is_narcissistic
function to identify narcissistic numbers, which are then printed to the console.
This simple Python script efficiently discovers narcissistic numbers, showcasing the power and flexibility of Python in exploring mathematical curiosities and programming challenges.
[tags]
Python, Narcissistic Numbers, Armstrong Numbers, Programming, Mathematics, Algorithms