Check Automorphic Number in Java

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

What you’ll learn

  • The automorphic condition in base 10: n^2 ends with the same decimal representation as n.
  • Two equivalent Java patterns: n^2 % 10^k and digit-by-digit comparison from the right.
  • Why long matters for the square, and why integer 10^k beats Math.pow for exact modulus.
  • 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^2 = 625 ends in 25. This is not the same idea as “circular” numbers from other puzzles — those refer to different digit patterns.

Two programs

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

Live preview

See n^2, 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.

  • Java basics: class Main, public static void main(String[] args), methods, and System.out.println.
  • The idea that n % m reads the remainder after division by m (here, powers of 10).
  • Optional contrast with the Armstrong number program (digit powers instead of suffix).

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 n^2 equal n. Equivalently,

n^2 mod 10^k = n.

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

Automorphic suffix of n^2 equals n
Not automorphic suffix != n
Not “circular” different concept

Mathematical definition

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

Worked example: n = 76

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

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

Intuition and examples

Write n^2 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, n^2, and the last k digits of the square.

76 Automorphic
Square
76^2 = 5776
Last 2 digits
76
Verdict
Suffix matches nautomorphic.
12 Not automorphic
Square
12^2 = 144
Last 2 digits
44
Verdict
44 != 12 — not automorphic.
25 Automorphic
Square
25^2 = 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 n^2 in general.

Live preview

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

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

Use integers n >= 1. For n > 10^9, use the Java programs with appropriate wide types instead.

Live result
Press “Run check” to see n^2, 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 n^2 and the modulus 10^k

Store n^2 in a wide integer type. Build 10^k with a loop, not floating Math.pow.

Compare suffix to n

Return true if (n^2) % 10^k == n. Alternatively, peel matching low digits from n and n^2 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 10^k with a short loop so the modulus stays exact. The square lives in a long.

java
public class Main {
    static long pow10(int k) {
        long p = 1L;
        for (int i = 0; i < k; i++) {
            p *= 10L;
        }
        return p;
    }

    // Returns true if n is automorphic in base 10, false otherwise (n > 0)
    static boolean isAutomorphic(int num) {
        if (num <= 0) {
            return false;
        }

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

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

        return square % mod == num;
    }

    public static void main(String[] args) {
        int number = 76;

        if (isAutomorphic(number)) {
            System.out.println(number + " is an automorphic number.");
        } else {
            System.out.println(number + " is not an automorphic number.");
        }
    }
}

Explanation

The last k decimal digits of a non-negative integer x are exactly x % 10^k when 10^k 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 * (long) num;

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

long mod = pow10(k);

Exact modulus base. Replacing this with Math.pow(10, k) risks off-by-one rounding once k grows.

return square % mod == num;

Suffix test. Compare the trimmed tail of n^2 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 n^2. No Math.pow is required.

java
public class Main {
    static boolean isAutomorphicPeel(int number) {
        if (number <= 0) {
            return false;
        }

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

        int n = number;
        long sq = square;
        while (n > 0) {
            if (n % 10 != sq % 10) {
                return false;
            }
            n /= 10;
            sq /= 10;
        }
        return true;
    }

    public static void main(String[] args) {
        int start = 1;
        int end = 50;

        System.out.println("Automorphic numbers in the range " + start + " to " + end + ":");
        for (int i = start; i <= end; i++) {
            if (isAutomorphicPeel(i)) {
                System.out.print(i + " ");
            }
        }
        System.out.println();
    }
}

Explanation

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

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

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

sq /= 10;

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

Optimization

Precompute 10^k. 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], only add cheap checks (like last digit patterns) when you can prove they are correct shortcuts.

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

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). Mixing these terms 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 works in floating point, which can round incorrectly for larger k. Computing 10^k with a small integer loop on long 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 Integer.MAX_VALUE, the square needs a wide type even before taking the modulus.

🔄 Input / output examples

For the single-number program, change the literal number variable or read it using Scanner.

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 n^2 can wrap and the suffix test becomes meaningless.

Floats

Math.pow(10, k)

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

Zero

Digit count k = 0

A naive digit loop on 0 can give k = 0 and 10^0 = 1, which may wrongly mark 0 as automorphic in sloppy code. The samples return false for n <= 0.

Modulus size

10^k overflow

For very large k, pow10(k) itself can exceed 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: n^2 ends with n in decimal ↔ n^2 % 10^k == n for k digits.
  • Code: wide square, exact 10^k, 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^2 = 625 ends in 25. So is 76 (76^2 = 5776). These are not the same as “circular” or cyclic numbers — those describe different digit-rotation patterns.

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