Monday, November 11, 2019

Python Program to Display Armstrong Numbers

In this post we'll see a Python program to display Armstrong numbers with in the given range.

An Armstrong number is a number that is equal to the sum of the digits in a number raised to the power of number of digits in the number.

For example 371 is an Armstrong number. Since the number of digits here is 3, so

371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

Another Example is 9474, here the number of digits is 4, so

9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

Display Armstrong numbers Python program

In the program user is prompted to input lower and upper range for displaying Armstrong numbers. Then run a for loop for that range checking in each iteration whether an Armstrong number or not.

def display_armstrong(lower, upper):
    for num in range(lower, upper + 1):
        digitsum = 0
        temp = num
        # getting length of number
        no_of_digits = len(str(num))
        while temp != 0:
            digit = temp % 10
            # sum digit raise to the power of no of digits
            digitsum += (digit ** no_of_digits)
            temp = temp // 10
        # if sum and original number equal then Armstrong number
        if digitsum == num:
            print(num, end=' ')


def get_input():
    """Function to take user input for display range"""
    start = int(input('Enter start number for displaying Armstrong numbers:'))
    end = int(input('Enter end number for displaying Armstrong numbers:'))
    # call function to display Armstrong numbers
    display_armstrong(start, end)

# start program
get_input()

Output

Enter start number for displaying Armstrong numbers:10
Enter end number for displaying Armstrong numbers:10000
153 370 371 407 1634 8208 9474 

That's all for this topic Python Program to Display Armstrong Numbers. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Display Prime Numbers
  2. Convert String to float in Python
  3. Python Program to Count Number of Words in a String
  4. Check String Empty or Not in Python
  5. Comparing Two Strings in Python

You may also like-

  1. Ternary Operator in Python
  2. Polymorphism in Python
  3. Abstract Class in Python
  4. Magic Methods in Python With Examples
  5. Difference Between Comparable and Comparator in Java
  6. Semaphore in Java Concurrency
  7. Converting Enum to String in Java
  8. Sending Email Using Spring Framework Example