Algorithm LogbookAlgorithm Logbook

Armstrong Number

Basic Math

๐Ÿ“‹ Problem Statement

A number is an Armstrong number (narcissistic number) if it equals the sum of its own digits each raised to the power of the number of digits. For example, 153=13+53+33153 = 1^3 + 5^3 + 3^3. Write a function that returns True if a number is an Armstrong number.

๐Ÿ’ก Intuition

For a number with d=โŒŠlogโก10NโŒ‹+1d = \lfloor \log_{10} N \rfloor + 1 digits, it is Armstrong if N=โˆ‘ididN = \sum_{i} d_i^d where did_i are its digits. The key insight is that you need the total digit count before summing โ€” compute it once, then extract each digit using the modulo loop from Day 1.

๐Ÿ”ง Approach

  1. Count the number of digits: d = len(str(n)) or using โŒŠlogโก10NโŒ‹+1\lfloor \log_{10} N \rfloor + 1.
  2. Extract digits one by one using n % 10 and n // 10.
  3. For each digit, raise it to the power d and add to a running sum.
  4. Compare the sum to the original number.

โšก Complexity Analysis

Time

O(logโก10N)O(\log_{10} N) โ€” proportional to the number of digits

Space

O(1)O(1) โ€” only integer variables

โš ๏ธ Common Mistakes

  • Computing the number of digits inside the loop (recalculated wrongly as digits are removed)
  • Using n % 10 after modifying n without saving the original โ€” always save original = n
  • Only testing single-digit numbers (1โ€“9 are trivially Armstrong); test 153, 370, 371, 407

๐ŸŽฏ Final Thoughts

Armstrong numbers combine two patterns you've already seen: digit extraction (Day 1, Day 2) and exponentiation. The important lesson here is to compute num_digits once before the loop, not inside it.