Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to check for an Armstrong number in Python

MUPPIDI BHAVANA

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:

xyzw...=xn+yn+zn+wn...xyzw... = x^n + y^n + z^n + w^n ...

Where

n:length of xyzw... n: length\space of\space xyzw...

For example, 153153 is an Armstrong number because

153=13+53+33153 = 1^3 + 5^3 + 3^3

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

Enter your input and hit run! This code determines if a number is an Armstrong number

Explanation

The code assumes that a number has been inputted and stored in n.

  • Line 1: We calculate the length of n using len() and store it in length_n.
  • Line 2: We cast n as int and store it in original_n.
  • Lines 3–6: We use a for loop to store cubes of each of the digits of n in list. Next, we add all the elements of list and store the result in sum_n.
  • Lines 8–9: We print the output that suggests if n is an Armstrong number, that is if the sum of each of its digits’ cube equals n itself.

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring