Beginner Number Problems Python

Armstrong Number Program in Python

Check whether a number equals the sum of its digits each raised to the power of the number of digits, and list such numbers in a range.

  • TimeO(d) to check a number with d digits
  • SpaceO(1) for the arithmetic version, O(d) for the string version
  • Hints3
  • Read3 min
Quick answer

An Armstrong number equals the sum of its digits, each raised to the power of the number of digits. 153 has 3 digits and 1^3 + 5^3 + 3^3 = 153, so it is an Armstrong number. In Python, count the digits with len(str(n)), take each digit with n % 10 and n // 10, add digit ** count, and compare the total with the original number. From 1 to 1000 they are 1 to 9, 153, 370, 371 and 407.

Digit extraction with % and //Exponent operator **while looplen(str(n))
1

Problem statement

Write an Armstrong number program in Python.

  1. Check a three-digit number, for example 153, using cubes.
  2. Write the general version that works for any number of digits, for example 9474.
  3. Print all Armstrong numbers from 1 to 1000.
Input

A positive integer n.

Output

Whether n is an Armstrong number, or the list of Armstrong numbers in a range.

Examples

Example 1
Inputn = 153
Output153 is an Armstrong number

1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153.

Example 2
Inputn = 123
Output123 is not an Armstrong number

1^3 + 2^3 + 3^3 = 1 + 8 + 27 = 36, which is not 123.

Example 3
Inputn = 9474
Output9474 is an Armstrong number

4 digits, so use the 4th power: 6561 + 256 + 2401 + 256 = 9474.

Constraints

  • n >= 0
  • The 3-digit version is correct only for 3-digit numbers; use the n-digit version otherwise
2

Think before you code

Reveal the questions to ask yourself first
  • How do you get the last digit of a number, and how do you remove it?
  • Why must you keep a copy of the original number?
  • Is the power always 3, or does it depend on the number?
3

Hints

Open one at a time — try again after each.
1 Hint 1
digit = n % 10 gives the last digit, and n //= 10 removes it.
2 Hint 2
Count the digits first with len(str(n)), and raise each digit to that power.
3 Hint 3
Work on a copy (temp) so you can still compare with n at the end.
4

Approach

Reveal the step-by-step approach

The Armstrong rule

Take a number with d digits. Raise each digit to the power d and add them up. If the sum equals the number, it is an Armstrong number. (It is also called a narcissistic number.)

Number Digits d Sum of digit^d Armstrong?
153 3 1 + 125 + 27 = 153 Yes
370 3 27 + 343 + 0 = 370 Yes
123 3 1 + 8 + 27 = 36 No
9474 4 6561 + 256 + 2401 + 256 = 9474 Yes

Armstrong logic step by step

  1. Count the digits: d = len(str(n)).
  2. Copy n into temp and set total = 0.
  3. While temp > 0: digit = temp % 10, total += digit ** d, temp //= 10.
  4. The number is Armstrong if total == n.

Many lab sheets ask only for 3-digit numbers and use digit ** 3. That is fine for 153, but it gives the wrong answer for 9474, so learn the d-digit version too.

5

Dry run

Walk through the example step by step

n = 153, d = 3, temp = 153, total = 0:

temp | digit = temp % 10 | digit ** 3 | total | temp // 10
-----+-------------------+------------+-------+-----------
153  | 3                 | 27         | 27    | 15
15   | 5                 | 125        | 152   | 1
1    | 1                 | 1          | 153   | 0

total == 153 == n, so 153 is an Armstrong number.

6

Solution

Reveal the full Python solution
solution.py
def is_armstrong(n):
    digits = len(str(n))
    total = 0
    temp = n
    while temp > 0:
        digit = temp % 10
        total += digit ** digits
        temp //= 10
    return total == n


for n in [153, 370, 123, 9474, 9475]:
    print(n, "->", is_armstrong(n))

print("Armstrong numbers from 1 to 1000:")
print([n for n in range(1, 1001) if is_armstrong(n)])

Output:

153 -> True
370 -> True
123 -> False
9474 -> True
9475 -> False
Armstrong numbers from 1 to 1000:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]

Every single-digit number is an Armstrong number, because d = 1 and x ** 1 = x. Between 10 and 1000 there are only four: 153, 370, 371 and 407.

Check Armstrong number in Python: 3-digit version

This is the version most lab records start with.

n = int(input("Enter a three-digit number: "))
temp = n
total = 0
while temp > 0:
    digit = temp % 10
    total += digit ** 3
    temp //= 10
if total == n:
    print(n, "is an Armstrong number")
else:
    print(n, "is not an Armstrong number")
Enter a three-digit number: 153
153 is an Armstrong number
Enter a three-digit number: 154
154 is not an Armstrong number

Short n-digit version with a string

If the question allows strings, you can read the digits directly from str(n):

n = 1634
total = sum(int(d) ** len(str(n)) for d in str(n))
print(total, total == n)
1634 True

Armstrong numbers in a range in Python

Reusing the shorter check for 4-digit and 5-digit ranges:

def is_armstrong(n):
    digits = len(str(n))
    return n == sum(int(d) ** digits for d in str(n))


print([n for n in range(1000, 10000) if is_armstrong(n)])
print([n for n in range(10000, 100000) if is_armstrong(n)])
[1634, 8208, 9474]
[54748, 92727, 93084]

The C version is the Armstrong number program in C. The Java versions are check whether a number is an Armstrong number and print all Armstrong numbers between 1 and 1000.

TimeO(d) to check a number with d digits
SpaceO(1) for the arithmetic version, O(d) for the string version
7

Review before the interview

Common mistakes

  • Always using the power 3. That works for 3-digit numbers only, and wrongly rejects 9474 and 1634.
  • Comparing total with n after the loop has changed n to 0. Work on a copy such as temp.
  • Using / instead of //. In Python 3, / returns a float, so the digits come out as decimals and the total is wrong.
  • Writing digit ^ 3. In Python ^ is bitwise XOR, not power. Use **.

Edge cases to test

  • 0 returns True in this code, since d = 1 and the empty sum 0 equals 0. Some teachers start the range at 1.
  • Single digits 1 to 9 are all Armstrong numbers.
  • Negative numbers: str(-153) has 4 characters, so handle n < 0 separately or reject it.

Interview follow-ups

  • How would you count the digits without converting to a string?
  • How is a strong number different from an Armstrong number?
  • How would you find all Armstrong numbers with up to 6 digits faster?

Keep practising

Practising Python for interviews?

CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us