Program to check whether given number is Narcissistic number or not in Python

A Narcissistic number (also called an Armstrong number) is a number that equals the sum of its digits raised to the power of the number of digits. For example, 153 is narcissistic because 1³ + 5³ + 3³ = 153.

So, if the input is like 9474, then the output will be True as 9? + 4? + 7? + 4? = 6561 + 256 + 2401 + 256 = 9474.

Algorithm

To solve this, we will follow these steps −

  • Convert the number to string to get individual digits
  • Calculate the sum of each digit raised to the power of total number of digits
  • Return True if the sum equals the original number, otherwise False

Example

Let us see the following implementation to get better understanding −

class Solution:
    def solve(self, n):
        s = str(n)
        return n == sum(int(x)**len(s) for x in s)

ob = Solution()
print(ob.solve(9474))

The output of the above code is −

True

Step-by-Step Verification

Let's verify the calculation for 9474 −

def check_narcissistic_detailed(n):
    digits = str(n)
    num_digits = len(digits)
    
    print(f"Number: {n}")
    print(f"Digits: {list(digits)}")
    print(f"Number of digits: {num_digits}")
    
    total = 0
    calculation = []
    
    for digit in digits:
        digit_int = int(digit)
        power_result = digit_int ** num_digits
        total += power_result
        calculation.append(f"{digit_int}^{num_digits} = {power_result}")
    
    print("Calculation:", " + ".join(calculation))
    print(f"Sum: {total}")
    print(f"Is Narcissistic: {total == n}")
    
    return total == n

check_narcissistic_detailed(9474)
Number: 9474
Digits: ['9', '4', '7', '4']
Number of digits: 4
Calculation: 9^4 = 6561 + 4^4 = 256 + 7^4 = 2401 + 4^4 = 256
Sum: 9474
Is Narcissistic: True

Testing Multiple Numbers

Let's test the function with various numbers −

def is_narcissistic(n):
    s = str(n)
    return n == sum(int(x)**len(s) for x in s)

# Test with different numbers
test_numbers = [153, 371, 9474, 123, 407]

for num in test_numbers:
    result = is_narcissistic(num)
    print(f"{num}: {result}")
153: True
371: True
9474: True
123: False
407: True

Conclusion

A narcissistic number equals the sum of its digits raised to the power of the digit count. Use string conversion to extract digits and compare the calculated sum with the original number.

Updated on: 2026-03-25T10:54:13+05:30

900 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements