In Python, how can we determine whether an n-digit integer is an Armstrong number or not?

Associate
Joined
20 Jan 2023
Posts
5
Location
India
So, after reading and studying, I attempted 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...

Python:
#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))
 
I have no experience with Python, but I will say if rep==0 looks redundant; let the while loop complete and then process your output, there's no need to check for a specific point in the while loop in order to output the result. Also, any reason to use a while loop instead of a for loop?

The way you're extracting the digit to process is very nice, but not very easy to read. In JavaScript I would've converted the input number to a String and then iterate over the letters. Saves on fancy maths and is easier to read.

JavaScript:
let take_in; // this is the numeric input value from some source
let digits = take_in.toString();
let exponent = digits.length;
let sum = 0, msg;

digits.split("").forEach(digit => sum += Number(digit) ** exponent);

msg = sum === take_in ? "is an Armstrong number" : "is not an Armstrong number";

console.log(take_in, msg);
 
Last edited:
Just revisiting an old thread as I have just recently started to learn Python. This seems to work. I didn't play with too many numbers though.

Python:
def is_armstrong_number(num):
    # Convert the number to a string to calculate the length
    num_str = str(num)
    num_length = len(num_str)
    
    # Calculate the sum of the digits raised to the power of the length
    sum_of_digits = sum(int(digit) ** num_length for digit in num_str)
    
    # Check if the sum of the digits is equal to the original number
    return num == sum_of_digits

# Test the function with an example
number = int(input("Enter a number: "))
if is_armstrong_number(number):
    print(number, "is an Armstrong number.")
else:
    print(number, "is not an Armstrong number.")
 
Just revisiting an old thread as I have just recently started to learn Python. This seems to work. I didn't play with too many numbers though.

Should work, but will as @alec says fail for negative numbers or indeed any kind of bad input. But doing a needless round-trip integer->string->integer is woefully inefficient - doesn't really matter for this task, but something to be avoided in general.
 
Back
Top Bottom