Check Automorphic Number in JavaScript

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Digits & modulus

What you’ll learn

  • The automorphic condition in base 10: ends with the same decimal representation as n.
  • Two equivalent JavaScript patterns: n² mod 10k (with BigInt) and digit-by-digit comparison from the right.
  • Why BigInt helps for the square, and why an integer loop for 10k beats Math.pow(10, k) 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² = 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 scripts

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 using BigInt for exact large squares.

  • JavaScript basics: function, BigInt, console.log, and Math.floor for digit loops.
  • 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, prefer the full scripts with the same BigInt pattern in Node or a bundler environment.

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 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 BigInt loop so the modulus stays exact. The square uses BigInt as well.

JavaScript
function pow10Big(k) {
  let p = BigInt(1);
  for (let i = 0; i < k; i++) {
    p *= BigInt(10);
  }
  return p;
}

function digitCount(n) {
  let k = 0;
  let t = n;
  while (t > 0) {
    k++;
    t = Math.floor(t / 10);
  }
  return k;
}

/** @param {number} num  positive integer */
function isAutomorphic(num) {
  if (num <= 0) {
    return false;
  }
  const k = digitCount(num);
  const nb = BigInt(num);
  const square = nb * nb;
  const mod = pow10Big(k);
  return square % mod === nb;
}

const number = 76;

if (isAutomorphic(number)) {
  console.log(number + " is an automorphic number.");
} else {
  console.log(number + " is not an automorphic number.");
}
Try it Yourself

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.”

const square = nb * nb;

Widen before multiply. Squaring as a normal Number can lose precision; BigInt(num) keeps exact for the suffix test.

pow10Big(k)

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

return square % mod === nb;

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

2

Automorphic numbers in a range (digit peel)

Same predicate as Example 1, implemented by stripping matching low digits from n and . Uses BigInt for the square tail; no Math.pow required.

JavaScript
function isAutomorphicPeel(init) {
  if (init <= 0) {
    return false;
  }
  let num = init;
  let square = BigInt(init) * BigInt(init);

  while (num > 0) {
    if (num % 10 !== Number(square % BigInt(10))) {
      return false;
    }
    num = Math.floor(num / 10);
    square = square / BigInt(10);
  }

  return true;
}

const start = 1;
const end = 50;

console.log("Automorphic numbers in the range " + start + " to " + end + ":");

let line = "";
for (let i = start; i <= end; i++) {
  if (isAutomorphicPeel(i)) {
    line += i + " ";
  }
}
console.log(line.trim());
Try it Yourself

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 (num % 10 !== Number(square % BigInt(10))) return false;

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

square = square / BigInt(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 (parity, mod 10) only when you can prove correctness—do not guess wrong shortcuts.

Widen early. Use BigInt(n) before squaring whenever n is large enough that n * n as a Number would exceed Number.MAX_SAFE_INTEGER.

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 scripts here return false for n <= 0 so digit-based loops stay simple and match common positive-integer interview specs.
Floating-point powers can round wrong for large k. Computing 10^k with a small loop on BigInt (or a plain integer loop when n is small enough) stays exact.
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.
Above about sqrt(Number.MAX_SAFE_INTEGER), n*n as a Number loses precision. Use BigInt for the square and modulus (as in the samples) whenever n can be large.

🔄 Input / output examples

For the single-number script, swap the literal number or read from process.argv / a prompt for interactive runs.

Value of nTypical 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 script 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

Number square

Always use BigInt (or another exact path) before multiplying large n. Otherwise can round and the suffix test becomes meaningless.

Floats

Math.pow(10, k)

Use an integer loop to build 10k as BigInt. 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, pow10Big grows beyond practical memory/time in naive loops. That only happens when n is enormous; switch strategies 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 scripts 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 Number precision loss on the square 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