Python Program to Generate Armstrong (Narcissistic) Number

This python program generates Armstrong number in an interval given by user. Armstrong number is also known as Narcissistic number.

A number is said to be Armstrong or Narcissistic Number if it is equal to the sum of its own digits raised to the power of the number of digits in a given number.

Armstrong Numbers Example, number 371 is Armstrong number because: 33 + 73 + 13 = 371

Try: Check Armstrong Number Online & Generate Armstrong Numbers Online

Python Source Code: Generate Armstrong Numbers


# Generate Armstrong numbers in interval

# Function to count digit in number
def count_digit(n):
    count = 0
    while n:
        n //= 10
        count += 1
    return count

# Function to check Armstrong
def is_armstrong(n):

    if n< 0:
        return False
    
    number_copy = n
    arm_sum = 0
    digit = count_digit(n)
    while n:
        remainder = n%10
        arm_sum += remainder**digit
        n //= 10

    return arm_sum == number_copy



# Reading interval from user
min_value = int(input('Enter minimum value: '))
max_value = int(input('Enter maximum value: '))

# Looping & displaying if it is Armstrong
# Here min_vale & max_value are included
print('Armstrong numbers from %d to %d are:' %(min_value, max_value))
for i in range(min_value, max_value+1):
    if is_armstrong(i):
        print(i, end=' ')

Armstrong Generation: Output

Enter minimum value: -10
Enter maximum value: 10000
Armstrong numbers from -10 to 10000 are:
0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 

Armstrong Generation: Code Explanation

We first read min_value and max_value from user. Function is_armstrong() is used to check whether a given number is Armstrong or not. We loop from min_value to max_value and pass each number to is_armstrong() function. If this function returns True, then we print it.