How to check for an Armstrong number in Python
Overview
Any positive integer of length n is considered an Armstrong number if the number equals the sum of each of its digits raised to the power n. The following equation captures this condition:
Where
For example,
Example
The below Python code demonstrates how to determine if a number is an Armstrong number.
length_n = len(n)original_n = int(n)for i in n:list.append(int(i)**length_n)sum_n = sum(list)if sum_n == original_n: print(n, "is an Armstrong number")else: print(n, "is not an Armstrong number")
Enter the input below
Explanation
The code assumes that a number has been inputted and stored in n.
- Line 1: We calculate the length of
nusinglen()and store it inlength_n. - Line 2: We cast
nasintand store it inoriginal_n. - Lines 3–6: We use a
forloop to store cubes of each of the digits ofninlist. Next, we add all the elements oflistand store the result insum_n. - Lines 8–9: We print the output that suggests if
nis an Armstrong number, that is if the sum of each of its digits’ cube equalsnitself.