Check Automorphic Number in C#

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

What you’ll learn

  • The automorphic condition in base 10: ends with the same decimal representation as n.
  • Two equivalent C# patterns: n² mod 10k and digit-by-digit comparison from the right.
  • Why long matters for the square, and why an integer 10k loop beats rounding from Math.Pow.
  • A browser live preview, edge cases, and complexity notes for interviews.

Overview

An automorphic number (in base 10) is a positive integer n whose square ends in n. Example: 25² = 625 ends in 25. This is not the same idea as “circular” numbers from other puzzles—those are a different family of digit patterns.

Two programs

A single-value check (try 76) and a range scan (here 1 to 50).

Live preview

See , the last k decimal digits, and the verdict instantly.

Interview polish

Exact modulus, overflow-safe squares, and clean guards for n ≤ 0.

Prerequisites

You should be comfortable with integer division, the modulo operator %, and widening a multiply to long.

  • C# basics: using System;, a class Program, static void Main(), and Console.WriteLine.
  • The idea that n % m reads the remainder after division by m (here powers of ten).
  • Optional contrast with Armstrong numbers (digit powers), which is a different test.

What is an automorphic number?

Let k be the number of decimal digits of a positive integer n. Then n is automorphic (in base 10) when the last k decimal digits of equal n. Equivalently,

n² mod 10k = n.

Single-digit examples are immediate: 5² = 25 ends in 5; 6² = 36 ends in 6. Two-digit examples include 25 and 76.

Automorphic suffix of n² equals n
Not automorphic suffix ≠ n
Not “circular” different concept

Mathematical definition

Work in base B = 10. Write 10k for the modulus that keeps the lowest k decimal digits. If n has exactly k ≥ 1 decimal digits, then n is automorphic when n² ≡ n (mod 10k).

Worked example: n = 76

Here k = 2 and 10k = 100. Now 76² = 5776, and 5776 mod 100 = 76, so 76 is automorphic.

Trimorphic numbers are the cube analogue: ends in n in base 10. Automorphic always refers to the square here.

Intuition and examples

Write in decimal. Chop everything except the rightmost k digits, where k is how long n is. If what remains still reads as n, you have an automorphic number.

Each card shows n, , and the last k digits of the square.

76 Automorphic
Square
76² = 5776
Last 2 digits
76
Verdict
Suffix matches nautomorphic.
12 Not automorphic
Square
12² = 144
Last 2 digits
44
Verdict
44 ≠ 12 — not automorphic.
25 Automorphic
Square
25² = 625
Last 2 digits
25
Verdict
Classic two-digit example.

Takeaway: the modulus is always tied to the length of n in decimal, not to the value of in general.

Live preview

Enter a positive integer n. The widget uses JavaScript BigInt for so modestly large n stay exact. Values above 109 are blocked to keep the tab responsive.

  1. Try 76, 25, or 12.
  2. Press Run check (or Enter).
  3. Read , the extracted suffix, and the verdict.

Use integers n ≥ 1. For n > 109, use the C# programs with appropriate wide types instead.

Live result
Press “Run check” to see n², the suffix, and the verdict.

Algorithm

Goal: decide whether a given positive integer n is automorphic in base 10.

Validate n

Reject n ≤ 0 if you only define automorphic numbers for positive integers.

Count decimal digits k

Repeatedly divide a temporary copy of n by 10 until it becomes 0.

Form and the modulus 10k

Store in a wide integer type. Build 10k with a loop, not floating Math.Pow.

Compare suffix to n

Return true if (n²) mod 10k == n. Alternatively, peel matching low digits from n and until n is exhausted.

📜 Pseudocode

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

function pow10(k):
    p ← 1
    repeat k times:
        p ← p * 10
    return p

function isAutomorphic(n):
    if n <= 0:
        return false
    k ← digitCount(n)
    sq ← n * n   // wide integer
    return (sq mod pow10(k)) = n
1

Check a single number (suffix modulus)

Computes 10k with a short loop so the modulus stays exact. The square lives in long.

c#
using System;

class Program
{
    static long Pow10Long(int k)
    {
        long p = 1;
        for (int i = 0; i < k; i++)
        {
            p *= 10L;
        }
        return p;
    }

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

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

        long square = (long)num * num;
        long mod = Pow10Long(k);

        return square % mod == num;
    }

    static void Main()
    {
        int number = 76;

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

Explanation

The last k decimal digits of a non-negative integer x are exactly x mod 10k when 10k fits your integer type.

if (num <= 0) return false;

Positive definition here. Avoids a digit count of 0 and keeps the story aligned with interview prompts that say “given a natural number.”

long square = (long)num * num;

Widen before multiply. Squaring in int can overflow even when the final suffix would have been well-defined.

Pow10Long(k)

Exact modulus base. Replacing this with (long)Math.Pow(10, k) risks rounding once k grows.

square % mod == num

Suffix test. Compare the trimmed tail of to the original n.

2

Automorphic numbers in a range (digit peel)

Same predicate as Example 1, implemented by stripping matching low digits from n and . Uses long for the square so the peel stays safe.

c#
using System;

class Program
{
    static bool IsAutomorphicPeel(int number)
    {
        if (number <= 0)
        {
            return false;
        }

        long square = (long)number * number;
        int n = number;

        while (n > 0)
        {
            if (n % 10 != square % 10)
            {
                return false;
            }
            n /= 10;
            square /= 10;
        }

        return true;
    }

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

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

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

        Console.WriteLine();
    }
}

Explanation

Each iteration checks one decimal place from the right. If every digit of n matches the corresponding tail digit of , the number is automorphic.

if (n % 10 != square % 10) return false;

Local mismatch test. As soon as a digit disagrees, you can stop.

square /= 10;

Shift the square tail. Integer division drops the matched low digit for the next comparison.

Optimization

Precompute 10k. If you test many values with the same digit length, reuse one modulus instead of rebuilding it each time.

Batch filters. In a tight loop over [1, U], combine cheap rejects only when you can prove correctness—do not guess wrong shortcuts.

Widen early. Promote n to long before squaring whenever n can exceed about sqrt(int.MaxValue).

Interview: be ready to state both the modulus form and the digit-peel form; they are the same mathematics.

❓ FAQ

In base 10, a positive integer n is automorphic if n squared ends with the same decimal digits as n. Equivalently, if n has k digits, then n^2 mod 10^k equals n.
No. Automorphic refers to the suffix of n^2 matching n. Circular (or cyclic) numbers usually mean something else (digit rotations related to 1/n). The old wording conflating them is incorrect.
Some definitions allow 0 because 0^2 = 0. The sample programs here return false for n <= 0 so digit-based loops stay simple and match common positive-integer interview specs.
Math.Pow returns double. Large k can introduce rounding before you cast to long. Building 10^k with an integer loop is exact for typical interview sizes.
Let k be the number of decimal digits of n. Counting digits and either the digit-stripping loop or forming 10^k are O(k), and k is Theta(log n), so the test is O(log n) for a fixed base.
Use long for the square (as in the samples). If n can be near int.MaxValue, the square needs a wide type even before taking the modulus.

🔄 Input / output examples

For the single-number program, swap the literal number or use int number = int.Parse(Console.ReadLine() ?? "0"); for interactive runs.

Value of numberTypical line printed
7676 is an automorphic number.
1212 is not an automorphic number.
55 is an automorphic number.
00 is not an automorphic number. (with the sample guard)

For the range program with 1 to 50:

Console
Automorphic numbers in the range 1 to 50:
1 5 6 25

Edge cases and pitfalls

Most failures are overflow on the square, a bad modulus from Math.Pow, or mishandling n = 0 when counting digits.

Overflow

int square

Always widen n before multiplying. Otherwise can wrap and the suffix test becomes meaningless.

Floats

Math.Pow(10, k)

Use an integer loop to build 10k. Floating rounding can break the modulus for larger k.

Zero

Digit count k = 0

A naive digit loop on 0 gives k = 0 and 100 = 1, which can wrongly mark 0 as automorphic in sloppy code. The samples return false for n ≤ 0.

Modulus size

10k overflow

For very large k, Pow10Long itself exceeds long. That only happens when n is enormous; switch strategies or types if your problem needs that range.

⏱️ Time and space complexity

TaskTimeExtra space
Single test (digit count + modulus or peel)O(k) with k = O(log n) digitsO(1)
All n in [1, U]O(U log U) digit work (naive loop)O(1)

Both sample programs use only a few scalars beyond the call stack.

Summary

  • Definition: ends with n in decimal ↔ n² mod 10k = n for k digits.
  • Code: wide square, exact 10k, or digit-by-digit peel from the right.
  • Watch-outs: do not confuse with circular numbers; avoid int overflow and Math.Pow rounding on the modulus.
Did you know?

In base 10, 25 is automorphic because 25² = 625 ends in 25. So is 76 (76² = 5776). These are not the same thing as “circular” or cyclic numbers—those refer to different digit-rotation ideas.

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