Find the Armstrong Numbers between Two Intervals using Python

Find the Armstrong Number in a given Range in Python

Given two integers high and low for limits as inputs, the objective is to write a code to Find the Armstrong Numbers in a given Interval in C++. 

For Instance,
Input : 150 160
Output : 153
Armstrong Numbers Between Two Intervals in python

Find the Armstrong Numbers in a given Range in Python

Given two integer inputs as intervals high and low, the objective is to write a python code to check if the numbers lying within the given interval are Armstrong Numbers or not.

An Armstrong number or a Narcissistic number is any number that sums up itself when each of its digits is raised to the power of a total number of digits in the number. Let us try to understand this through the below example,

  • abcd… = an + bn + cn + dn + …
  • Where n is the order(length/digits in number)

Let’s look at some examples of Armstrong Numbers.

Examples

Here are few examples that’ll help you to understand the concept better.

Find the Armstrong Number in a given Interval in Python

Method 1

Python Code

Run
low, high = 10, 10000

for n in range(low, high + 1):

    # order of number
    order = len(str(n))

    # initialize sum
    sum = 0

    temp = n
    while temp > 0:
        digit = temp % 10
        sum += digit ** order
        temp //= 10

    if n == sum:
        print(n, end=", ")

Method 2

Python Code

Run
import math

first, second = 150, 10000


def is_Armstrong(val):
    sum = 0

    # this splits the val into its digits
    # example val : 153 will become [1, 5, 3]
    arr = [int(d) for d in str(val)]

    # now we iterate on array items (digits)
    # add these (digits raised to power of len i.e order) to sum
    for i in range(0, len(arr)):
        sum = sum + math.pow(arr[i], len(arr))

    # if sum == val then its armstrong
    if sum == val:
        print(str(val) + ", ", end="")


for i in range(first, second + 1):
    is_Armstrong(i)

Output

153, 370, 371, 407, 1634, 8208, 9474, 

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

15 comments on “Find the Armstrong Numbers between Two Intervals using Python”


  • Rithick

    n=int(input(‘Number : ‘))
    x=str(n)
    p=len(x)
    amstrong=0

    for i in x:
    amstrong+=int(i)**p
    if n==amstrong:
    print(“Amstrong”)
    else:
    print(“Not Amstrong”)


  • Raghvendra Singh Shekhawat

    lower_number = int(input(“Enter any positive number: “))
    higher_number = int(input(“Enter any positive number: “))

    for i in range(lower_number,higher_number+1):
    sum = 0
    length = len(str(i))
    original = i

    while i > 0:
    digit = i % 10
    sum += digit ** length
    i = i // 10

    if sum == original:
    print (original ,end=”, “)