-
Active Member
In Python, how can we determine whether an n-digit integer is an Armstrong number or not?
I was attempting to answer a question. Assume a user enters an n-digit number. How do we know if it's Armstrong or not? One technique may be to record a list of all Armstrong numbers and then check from that list, but I wanted to use a different approach. This is my code:
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))
-
Member
This is just the basics of how to calculate it in Python. Adapt it to your own purposes.
Code:
# Store user input and create additional variables for calculation
User_Input = int(input("Enter an integer: "))
User_Integer = User_Input
Armstrong_Sum = 0
# Find length of number. This will be used for the calculation as well as our counter.
length = len(str(User_Input))
counter = len(str(User_Input))
# Calculation
while counter > 0:
# Modulo gives the "ones" placement value for multiplication by power of length.
Armstrong_Sum += (User_Integer % 10) ** length
# Floor division to remove the existing "ones" place.
User_Integer //= 10
counter -= 1
# Comparison
if Armstrong_Sum == User_Input:
print(True)
else:
print(False)
Wikipedia also has an article on this with a Python example.
Narcissistic number - Wikipedia
-
Post Thanks / Like - 1 Thanks
YreiauW (1 members gave Thanks to JohnArmstrong for this useful post)