Skip to content

Volume ITechnology

4.0.4 — Armstrong, Perfect and Strong Numbers ​

Classic · Easy · very common in service-company online tests

These numbers have no practical use. They are asked because each one tests a loop you will use everywhere: peeling digits, finding divisors, and reusing a value you computed earlier.

The problem ​

Write a check for each kind of number, and print every one up to a limit.

  • An Armstrong number equals the sum of its digits, each raised to the power of how many digits it has. 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27.
  • A perfect number equals the sum of its divisors, not counting itself. 28 = 1 + 2 + 4 + 7 + 14.
  • A strong number equals the sum of the factorials of its digits. 145 = 1! + 4! + 5! = 1 + 24 + 120.

1. Armstrong numbers ​

Mathematicians call these narcissistic numbers, because each one is made from its own digits. The name "Armstrong" comes from computer-science teaching, where it became the standard name for this exercise. In 1940 the mathematician G. H. Hardy mentioned 153 and its friends as an example of facts that are curious but have no importance. He was right, which is exactly why they make a clean exercise.

python
def is_armstrong(n: int) -> bool:
    power = len(str(n))       # (1)
    total, m = 0, n
    while m > 0:
        total += (m % 10) ** power   # (2)
        m //= 10
    return total == n          # (3)

print(is_armstrong(153))    # → True
print(is_armstrong(9474))   # → True
print(is_armstrong(154))    # → False
print([x for x in range(1, 1000) if is_armstrong(x)])
# → [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]

(1) The power is the number of digits. 153 has 3 digits, so each digit is cubed. 9474 has 4, so each is raised to the 4th power: 9^4 + 4^4 + 7^4 + 4^4 = 6561 + 256 + 2401 + 256 = 9474.

(2) The digit loop, with each digit raised to the power before it is added.

(3) We worked on a copy m, so n still holds the original for the comparison. Destroying n inside the loop and then comparing with it is the most common bug on this problem.

Common mistake. Many people always cube the digits, because 153 is the famous example. That is only right for 3-digit numbers. Every single-digit number is an Armstrong number, since d^1 = d. There are only 88 Armstrong numbers in base 10 in total. The largest has 39 digits. Beyond that, a number with k digits is always bigger than the most its digits could ever add up to, k \times 9^k, so no more can exist.

2. Perfect numbers ​

Perfect numbers are among the oldest ideas in mathematics. Euclid wrote about them around 300 BC. Only four were known in ancient times: 6, 28, 496 and 8128.

The slow way tries every number from 1 to n - 1 as a divisor. That is n steps. There is a much faster way.

Divisors come in pairs. If d divides n, then so does n / d. For 28, the pairs are 1 \times 28, 2 \times 14 and 4 \times 7. In every pair, one number is at most \sqrt{n} and the other is at least \sqrt{n}. Why? If both were bigger than \sqrt{n}, their product would be bigger than \sqrt{n} \times \sqrt{n} = n. So you only need to search up to \sqrt{n}. Each divisor you find there gives you its partner for free.

python
def is_perfect(n: int) -> bool:
    if n < 2:
        return False
    total = 1                     # (1)
    d = 2
    while d * d <= n:             # (2)
        if n % d == 0:
            total += d
            partner = n // d
            if partner != d:      # (3)
                total += partner
        d += 1
    return total == n

print(is_perfect(28))    # → True
print(is_perfect(12))    # → False
print([x for x in range(1, 10000) if is_perfect(x)])   # → [6, 28, 496, 8128]

(1) 1 divides every number, so start the total at 1. We skip n itself, as the definition says.

(2) d * d <= n means the same as d <= sqrt(n), but it uses only whole numbers. Square roots are calculated with decimals, which can be slightly off for very large numbers.

(3) When n is a perfect square, like 36, the divisor 6 pairs with itself. Without this check, 6 would be added twice.

For 28 the loop tries d = 2, 3, 4, 5, because 6 \times 6 = 36 > 28. It finds 2 (partner 14) and 4 (partner 7). The total is 1 + 2 + 14 + 4 + 7 = 28. That is four steps instead of twenty-seven.

Every even perfect number has one shape. Euclid proved that when 2^p - 1 is prime, the number 2^{p-1}(2^p - 1) is perfect. For p = 2 that gives 2 \times 3 = 6. For p = 3 it gives 4 \times 7 = 28. Two thousand years later, Leonhard Euler proved that every even perfect number has this shape. Nobody has ever found an odd perfect number, and nobody has proved one cannot exist. It is one of the oldest unsolved problems in mathematics.

3. Strong numbers ​

A strong number equals the sum of the factorials of its digits. The factorial d! is 1 \times 2 \times \dots \times d, with 0! = 1 by definition.

A digit is always between 0 and 9. So there are only ten possible factorials. Calculating them again for every digit of every number would be wasteful. Compute them once and look them up.

python
FACT = [1] * 10
for d in range(1, 10):
    FACT[d] = FACT[d - 1] * d        # (1)

def is_strong(n: int) -> bool:
    total, m = 0, n
    while m > 0:
        total += FACT[m % 10]        # (2)
        m //= 10
    return total == n

print(FACT)    # → [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
print([x for x in range(1, 100000) if is_strong(x)])   # → [1, 2, 145, 40585]

(1) Each factorial is the one before it times the next number. 5! = 4! \times 5 = 24 \times 5 = 120. One multiplication each.

(2) Look up the factorial of the digit instead of computing it.

There are exactly four strong numbers in base 10: 1, 2, 145 and 40585. The reason is like the Armstrong limit. An 8-digit number is at least 10,000,000. But its digit factorials add up to at most 8 \times 9! = 2{,}903{,}040. That is too small, so no strong number can have 8 or more digits. A search to 10 million is a complete search.

Three more you may be asked ​

Each is a one-line idea built on the digit loop.

  • Harshad number: divisible by the sum of its digits. 18 is one, because 1 + 8 = 9 and 9 divides 18. Check: n % digit_sum(n) == 0.
  • Neon number: the digits of its square add up to the number. 9^2 = 81, and 8 + 1 = 9.
  • Automorphic number: its square ends with the number itself. 25^2 = 625, 76^2 = 5776. Check: str(n * n).endswith(str(n)).

Complexity ​

The Armstrong and strong checks are O(\text{digits}), which is O(\log n). The perfect check is O(\sqrt{n}), compared with O(n) for the slow way. For n = 10^{12} that is a million steps instead of a trillion.

What the interviewer will push on ​

These are the questions that usually come right after you solve it. Each one has a short, plain answer you can say out loud.

"Is 9474 an Armstrong number?" Yes. It has 4 digits, so each digit is raised to the power 4, not cubed. 9^4 + 4^4 + 7^4 + 4^4 = 9474. Always use the number of digits as the power.

"How do you find divisors faster than trying every number?" Divisors come in pairs, like 2 and 14 for 28. One number of each pair is always at most \sqrt{n}. So try numbers only up to \sqrt{n}, and add both members of each pair. For a perfect square, like 36, do not add 6 twice.

"Why did you store the factorials of 0 to 9 first?" A digit can only be 0 to 9. Working out the same ten factorials again for every digit wastes time. Computing them once and looking them up is faster.

"Your Armstrong check always says False. Why?" The usual cause is changing n inside the loop and then comparing the sum with the changed n. Work on a copy of n inside the loop.

One thing to volunteer: "The square-root trick for finding divisors is the same trick used to check if a number is prime."

Next: 4.0.5 Prime Numbers. Checking one number, listing many, and breaking a number into its prime factors.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet