Check Armstrong Number in C#

Beginner
⏱️ 12 min read
📚 Updated: May 2026
🎯 2 Code Examples
Digits & powers

What you’ll learn

  • The Armstrong (narcissistic) condition in base 10: sum of each digit raised to the number of digits.
  • A precise algorithm, pseudocode, and two C# programs: one number and a range scan.
  • Why integer exponentiation is safer than raw Math.Pow casts for exact checks, plus edge cases and complexity.
  • A browser live preview that mirrors the same digit-power rule.

Overview

An Armstrong number equals the sum of its decimal digits, each raised to the power of how many digits it has. Classic example: 153 = 1³ + 5³ + 3³. This tutorial shows how to implement that test in C#, then scan a range.

Two programs

A single-value check (try 153) and a range listing from 1 to 200 so you see one-digit Armstrong numbers plus 153.

Live preview

See digit count k, the expanded sum of each dk, and the verdict without compiling.

Interview polish

Guards for n ≤ 0, integer powers, overflow notes, and complexity in one place.

Prerequisites

Comfort with loops, integer division, and the modulo operator % is enough to follow the code.

  • C# basics: using System;, a class Program, static void Main(), and Console.WriteLine.
  • Extracting the last digit with n % 10 and shifting with n / 10.
  • Optional: comparing this idea to amicable and abundant problems (different rules, same “loop over structure of n” pattern).

What is an Armstrong number?

Let n be a positive integer with k decimal digits. Write those digits as dk-1 … d1 d0 (most significant to least). Then n is an Armstrong number (in base 10) when

dk-1k + … + d1k + d0k = n.

The exponent is always the digit count, not the value of the digit. Same idea generalizes to other bases; here we stay in decimal.

Armstrong sum of (each digit)k = n
Not Armstrong that sum ≠ n
Synonyms narcissistic / PPDI (base 10)

Mathematical definition

Fix base b = 10. If n has k decimal digits ak-1, …, a0 (most significant to least), then n is Armstrong when ak-1k + … + a0k = n.

Three-digit template

For 100 ≤ n ≤ 999, write n = 100a + 10b + c with digits a,b,c. Armstrong means a³ + b³ + c³ = 100a + 10b + c.

Examples: 153, 370, 371, 407 are the only three-digit Armstrong numbers besides the trivial one-digit cases.

Intuition and examples

Count how many digits n has. Peel digits off from the right with % 10 and / 10, raising each peel to that count and adding into a running total. If the total lands back on n, you have an Armstrong number.

Each card shows the digit-power sum with the same exponent k everywhere.

153 Armstrong
Digits
3, so exponent 3
Sum
1³ + 5³ + 3³ = 1 + 125 + 27 = 153
Verdict
Equals nArmstrong.
123 Not Armstrong
Digits
3, exponent 3
Sum
1³ + 2³ + 3³ = 1 + 8 + 27 = 36
Verdict
36 ≠ 123 — not Armstrong.
7 Armstrong
Digits
1, exponent 1
Sum
7¹ = 7
Verdict
Every 1–9 works the same way.

Takeaway: the exponent is the length of n in decimal, not “how big the digit feels.”

Live preview

Type a positive integer n. The widget counts decimal digits k, builds the sum of each digit to the kth power, and compares it to n. Caps at 999 999 999 to keep JavaScript arithmetic predictable.

  1. Try 153, 123, or a single digit.
  2. Press Run check (or Enter).
  3. Read the expanded sum line and the verdict.

Use integers n ≥ 1. Very large n may hit precision limits in the browser before the code section’s overflow notes matter.

Live result
Press “Run check” to see digit powers and the verdict.

Algorithm

Goal: decide whether a given n is an Armstrong number in base 10.

Validate n

If n ≤ 0, return false (or follow your problem’s convention explicitly).

Count digits k

Copy n to a temporary variable and repeatedly divide by 10 until it becomes 0, counting iterations.

Accumulate digit powers

Walk digits again with % 10 and / 10. Add digit^k to a running sum using exact integer exponentiation.

Compare

If the sum equals the original n, return true; otherwise false.

📜 Pseudocode

Pseudocode
function digitCount(n):
    k ← 0
    t ← n
    while t > 0:
        k ← k + 1
        t ← floor(t / 10)
    return k

function sumDigitPowers(n, k):
    sum ← 0
    t ← n
    while t > 0:
        d ← t mod 10
        sum ← sum + (d to the power k)   // integer power
        t ← floor(t / 10)
    return sum

function isArmstrong(n):
    if n <= 0:
        return false
    k ← digitCount(n)
    return sumDigitPowers(n, k) = n
1

Check a single number (program with explanation)

Uses a small Ipow helper so every step stays in integer arithmetic—no floating-point Math.Pow rounding surprises.

c#
using System;

class Program
{
    static int Ipow(int baseVal, int exp)
    {
        int r = 1;
        for (int e = 0; e < exp; e++)
        {
            r *= baseVal;
        }
        return r;
    }

    static bool IsArmstrong(int number)
    {
        if (number <= 0)
        {
            return false;
        }

        int k = 0;
        int t = number;
        while (t > 0)
        {
            k++;
            t /= 10;
        }

        t = number;
        int sum = 0;
        while (t > 0)
        {
            int d = t % 10;
            sum += Ipow(d, k);
            t /= 10;
        }

        return sum == number;
    }

    static void Main()
    {
        int number = 153;

        if (IsArmstrong(number))
        {
            Console.WriteLine($"{number} is an Armstrong number.");
        }
        else
        {
            Console.WriteLine($"{number} is not an Armstrong number.");
        }
    }
}

Explanation

Two passes over the digits: first to learn k, second to sum dk for each decimal digit d.

if (number <= 0) return false;

Guard non-positive inputs. Digit count is ambiguous for 0, and negatives are not in the usual definition used here.

while (t > 0) { k++; t /= 10; }

Count digits. Integer division by ten strips one decimal digit per iteration.

sum += Ipow(d, k);

Same exponent for every digit. That is what distinguishes Armstrong numbers from other digit games.

return sum == number;

Final comparison against the original value, not the working copy used while peeling digits.

2

Armstrong numbers in a range

Same IsArmstrong helper as Example 1, wrapped in a loop from 1 to 200 (shows digits 1–9 plus 153).

c#
using System;

class Program
{
    static int Ipow(int baseVal, int exp)
    {
        int r = 1;
        for (int e = 0; e < exp; e++)
        {
            r *= baseVal;
        }
        return r;
    }

    static bool IsArmstrong(int num)
    {
        if (num <= 0)
        {
            return false;
        }

        int k = 0;
        int t = num;
        while (t > 0)
        {
            k++;
            t /= 10;
        }

        t = num;
        int sum = 0;
        while (t > 0)
        {
            int d = t % 10;
            sum += Ipow(d, k);
            t /= 10;
        }

        return sum == num;
    }

    static void Main()
    {
        int start = 1;
        int end = 200;

        Console.WriteLine($"Armstrong numbers in the range {start} to {end}:");

        for (int i = start; i <= end; i++)
        {
            if (IsArmstrong(i))
            {
                Console.Write($"{i} ");
            }
        }

        Console.WriteLine();
    }
}

Explanation

The outer loop is linear in the width of the interval; the inner test is logarithmic in each i.

for (int i = start; i <= end; i++)

Brute enumeration. Change start and end to whatever bounds you need.

if (IsArmstrong(i)) Console.Write($"{i} ");

Filter with the same predicate as the single-number program—no duplicated logic beyond keeping one helper in your file.

Optimization

Exponentiation. For fixed digit count k, precompute 0^k … 9^k in a table of length 10 and replace Ipow(d,k) with a lookup when scanning many numbers.

Bounds on sums. For a given k, the maximum digit-power sum is 9^k · k. Prune candidate n values outside plausible intervals when generating large lists.

Wide integers. Promote the accumulator to long before comparing to n if powers can overflow int.

Interview: state the O(log n) digit pass clearly; mention lookup tables only if they ask for faster range generation.

❓ FAQ

In base 10, a positive integer n is an Armstrong number (also called narcissistic) if n equals the sum of its decimal digits, each raised to the power of the total number of digits. Example: 153 has three digits and 1^3 + 5^3 + 3^3 = 153.
Yes. For a one-digit n, the digit count is 1, and n^1 = n, so every digit 1 through 9 is Armstrong. Whether to include 0 depends on the problem statement; this page treats n <= 0 as not Armstrong.
Math.Pow works with double-precision floats. Casting back to int can round incorrectly for some combinations. Multiplying in a small integer loop keeps the check exact for typical interview-sized inputs.
Definitions vary. The sample programs return false for n <= 0 so digit counting stays well-defined and matches common specs that only ask for positive integers.
Let d be the number of decimal digits. Counting digits and summing digit powers are both O(d), and d is Theta(log n), so the whole test is O(log n) for a fixed base.
The sum of digit powers can exceed 32-bit int before you compare to n. Use long for the accumulator (and sometimes for n) when the problem allows large inputs.

🔄 Input / output examples

For the single-number program with a literal number, typical lines look like this. For interactive runs you might use int number = int.Parse(Console.ReadLine() ?? "0");.

Value of numberTypical line printed
153153 is an Armstrong number.
123123 is not an Armstrong number.
77 is an Armstrong number.
00 is not an Armstrong number. (with the sample guard)

For the range program with start = 1 and end = 200:

Console
Armstrong numbers in the range 1 to 200:
1 2 3 4 5 6 7 8 9 153

Edge cases and pitfalls

Most bugs come from miscounting digits, reusing a mutated copy of n, or mixing floating-point Math.Pow into an integer test.

Input

n ≤ 0

Return false early. Otherwise 0 can slip through with a digit count of 0 in naive loops.

State

Losing the original n

Keep one variable for comparison and separate temporaries for counting and summing, or reassign from a saved copy.

Floats

Math.Pow rounding

Casting Math.Pow to int can be off by one for some values. Prefer integer exponentiation for exact equality tests.

Overflow

Partial sums

Digit powers add up quickly. Use long when k or the digits are large enough to overflow int.

⏱️ Time and space complexity

TaskTimeExtra space
Single IsArmstrong(n) (two digit passes, k = O(log n))O(log n)O(1)
Ipow(d, k) per digit (naive multiply loop)O(k) per callO(1)
All n in [1, U] with naive Ipowroughly O(U · log² U)O(1)
Same range with a fixed table for 0..9 to the power kO(U log U) digit workO(1) table

Auxiliary memory beyond the call stack is a handful of integers in both sample programs.

Summary

  • Definition: sum of each decimal digit raised to the digit-count power equals n.
  • Implementation: count digits, accumulate integer powers, compare to the original n; guard n ≤ 0 if required.
  • Watch-outs: avoid float rounding from Math.Pow, watch overflow on the sum, and keep the original value for the final equality.
Did you know?

Besides the trivial one-digit cases 19, the only three-digit Armstrong numbers are 153, 370, 371, and 407. For example, 1³ + 5³ + 3³ = 153.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful