Shimon Nawaz Loan
Shimon Nawaz Loan

Reputation: 11

How can we check whether an n-digit number is Armstrong number or not in Python?

I was trying to solve a question. Suppose a user enters n digit number. How can we check if its Armstrong or not. One approach could be to save a list of all Armstrong number and check from that list, but i wanted to approach it the other way. here is my code...

#armstrong number
take_in=int(input("Enter the number: "))
num2=take_in
length=len(str(take_in))
rep=length
summ=0
while rep>0:
    summ=summ+(num2/10**rep)**length
    num2=num2%(10**rep)
    rep=rep-1
    if rep==0:
        if summ==take_in:
            print("{} is an armstrong number".format(take_in))
        else:
            print("{} is not an armstrong number".format(take_in))

Upvotes: 1

Views: 198

Answers (2)

user 98
user 98

Reputation: 177

Here is the simplest way to find the Armstrong number in python.

   num = 153
   s1 = str(num)
   sum=0
   for i in s1:
    sum+=int(i)**len(s1)
   if sum==num:
     print('Given number is armstrong number :',num)
   else:
     print('Given number is not a armstrong number :',num)

Upvotes: 0

pho
pho

Reputation: 25479

An Armstrong number is an integer which is equal to the sum of each of its digits raised to the number of digits in the number. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

So once you have the length of the number, all you need to do is iterate over the digits and raise each of them to the length, and add them all. An easy way to iterate over the digits is to convert the number to a string and then iterate over the characters in the string.

So you'd have:

adds = 0
for digit in str(take_in):
    adds += int(digit)**length

isArmstrong = adds == take_in

Or using list comprehensions:

isArmstrong = sum([int(digit)**length for digit in str(take_in)]) == take_in

Upvotes: 1

Related Questions