Check Automorphic Number in Python

Beginner
⏱️ 11 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Digits & modulus

What You’ll Learn

An automorphic number’s square ends with the number itself. This tutorial covers the definition, a live preview, algorithm steps, worked Python examples, edge cases, and complexity.

Definition

n² ends in n

n is automorphic when the last digits of n² are exactly n.

Digit Count k

Find length

Use len(str(n)) so you know how many trailing digits to compare.

Modulus Suffix

n² % 10^k

The last k digits of n² equal (n * n) % (10 ** k).

Classic 76

76² = 5776

5776 ends with 76 — a golden interview example alongside 25.

Live Preview

Try any n

Type a number and see n², the modulus suffix, and the verdict.

O(log n)

Complexity

One check depends on digit count; extra space stays O(1).

Introduction

An automorphic number is a positive integer n whose square ends with the digits of n itself. If n has k digits, the check is simply (n * n) % (10 ** k) == n.

Famous base-10 examples include 5 (5² = 25), 6 (6² = 36), 25 (25² = 625), and 76 (76² = 5776). This tutorial treats only positive integers, so n <= 0 returns false.

Why it matters?

It trains digit counting, powers of ten, and modulus suffix tricks — tools that show up in many interview number problems.

Key Highlights

Suffix Match

Only the last k digits of n² must equal n.

Modulus Trick

% 10^k peels those last k digits in one shot.

Not Circular

Automorphic is a square-suffix property — different from cyclic numbers.

Python Big Ints

Squares grow fast; Python integers stay exact.

In short: count digits k, then check whether (n * n) % (10 ** k) equals n.

📝 Problem & Approach

Given a positive integer n, decide whether it is automorphic: whether n² ends with n.

python
# Example: n = 76 (k = 2)
# 76 * 76 = 5776
# 5776 % 100 == 76  → automorphic

Inputs & Outputs

ItemTypeDescription
nintPositive integer to test (this tutorial returns false for n <= 0).
Return / printbool / textTrue / message when the last k digits of n² equal n.

Minimal workflow

Pseudocode
function isAutomorphic(n):
    if n <= 0:
        return false
    k = number of digits of n
    return (n * n mod 10^k) == n

Method comparison

MethodIdeaNotes
Modulus suffix(n * n) % (10 ** k) == nInterview classic; O(1) extra space
String ends-withstr(n * n).endswith(str(n))Very readable; allocates strings

⚡ Quick Reference

GoalPattern
Digit count kk = len(str(n))
Mask for last k digits10 ** k
Square suffix(n * n) % (10 ** k)
Automorphic testsuffix == n
String variantstr(n * n).endswith(str(n))
Common examples1, 5, 6, 25, 76

📋 Modulus vs String vs Wrong Prefix Check

All look similar — only one idea is correct for automorphic.

Modulus
% 10^k

Best default for interviews; peels the suffix directly

endswith
str ends with

Clear and short; fine when readability wins

startswith
wrong idea

Automorphic cares about the end of n², not the start

Interview tip
explain % 10^k

Show you know why the modulus isolates last digits

Context

When This Problem Shows Up

Reach for automorphic drills when suffix checks and modulus matter.

  1. Interview warm-ups

    Quick check of digit count, powers of ten, and boolean returns.

  2. After Armstrong / digit topics

    Natural follow-up once students already count digits.

  3. Teaching modulus

    Makes % 10^k feel concrete with 25 and 76.

  4. Range listing tasks

    “Print all automorphic numbers from 1 to N” reuses one helper.

  5. Not for huge live demos alone

    Very large n make enormous squares — cap previews and discuss big integers.

Key benefit: one short problem that covers digit length, modulus suffixes, and O(log n) reasoning.

🔮 Live Preview

Enter a positive integer to see n², the last-k-digit suffix, and the verdict.

Use integers n ≥ 1 (preview capped at 1000000000).

Live result
Press "Run check" to see details.

Examples Gallery

Three complete Python programs — modulus check, range listing, and a string endswith variant. Click View Output to reveal sample console results.

📚 Getting Started

Modulus suffix — the interview default.

Example 1 — Check a Single Number

Count digits, take (n * n) % (10 ** k), and compare with n.

python
def is_automorphic(n: int) -> bool:
    if n <= 0:
        return False
    k = len(str(n))
    return (n * n) % (10 ** k) == n


number = 76
if is_automorphic(number):
    print(f"{number} is an automorphic number.")
else:
    print(f"{number} is not an automorphic number.")

How It Works

Guard non-positive inputs, compute k once, then isolate the last k digits of the square with modulus. Equality with n is the entire definition.

📈 Practical Patterns

Reuse the helper across a closed range.

Example 2 — Automorphic Numbers in a Range

Loop from start to end and print every value that passes the check.

python
def is_automorphic(n: int) -> bool:
    if n <= 0:
        return False
    k = len(str(n))
    return (n * n) % (10 ** k) == n


start, end = 1, 50
print(f"Automorphic numbers in the range {start} to {end}:")
for value in range(start, end + 1):
    if is_automorphic(value):
        print(value, end=" ")

How It Works

The helper stays pure; the outer loop only decides what to print. Within 1…50 you should see 1, 5, 6, and 25 — a useful self-check.

📄 Readable Variant

Same verdict with string suffix matching.

Example 3 — String endswith Check

Convert the square to text and ask whether it ends with the digits of n.

python
def is_automorphic(n: int) -> bool:
    if n <= 0:
        return False
    return str(n * n).endswith(str(n))


print(is_automorphic(25))
print(is_automorphic(12))

How It Works

endswith does the suffix comparison for you. 25² = 625 ends with “25”; 12² = 144 ends with “44”, so the second call is false.

🧠 How the Algorithm Decides

1

Validate n

If n <= 0, return false for this tutorial’s positive-integer definition.

Guard
2

Count digits

Set k = len(str(n)) (or count by dividing by 10).

Length
3

Take the suffix

Compute (n * n) % (10 ** k) to read the last k digits of the square.

Modulus
=

Compare to n

Return true only when that suffix equals the original number.

🔎 Worked Walkthrough — n = 76

Trace the modulus method. Digit count k = 2, so the mask is 10 ** 2 = 100.

StepExpressionResult
1k = len("76")2
276 * 765776
35776 % 10076
476 == 76True (automorphic)

Contrast: for n = 12, 144 % 100 = 44, which is not 12.

Use Cases

Where automorphic checks show up beyond the interview prompt.

1. Interview Coding

Warm-up for digit length and modulus suffixes.

Example: write is_automorphic(n).

2. Teaching % 10^k

Shows how modulus isolates the last k digits.

Example: chalkboard walkthrough of 76.

3. Range Filters

Print or count automorphic values inside bounds.

Example: all hits from 1 to 100.

4. Related Digit Problems

Skills transfer to other suffix / prefix number checks.

Example: trimorphic or Kaprekar follow-ups.

5. Complexity Practice

Argue O(log n) from digit count convincingly.

Example: “why is k = O(log n)?”

6. Big-Integer Awareness

Squares grow quickly; Python still keeps exact values.

Example: discuss fixed-width overflow in other languages.

Pro Tip: keep one is_automorphic helper and reuse it for single checks and range printers.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. One-Line Core Check

    After counting digits, the modulus comparison is a single clear expression.

  2. 2. Works for Any Digit Length

    Using k from the digit count handles 1-digit through multi-digit cases.

  3. 3. Tiny Extra Memory

    A few integers suffice for the modulus approach — O(1) extra space.

  4. 4. Easy Self-Checks

    5, 6, 25, 76 and 12 give instant confidence.

Pro Tip: say “last k digits of n²” out loud before coding — it prevents accidental startswith mistakes.

Usage Tips

Small habits that keep automorphic code interview-ready.

  1. 1. Count Digits First

    Compute k before squaring so the modulus mask matches the original length.

  2. 2. Prefer Modulus in Interviews

    It shows number sense; mention endswith only as an alternative.

  3. 3. Guard Non-Positive Inputs

    Return false early for n <= 0 unless the prompt includes 0.

  4. 4. Spot-Check Known Values

    Assert True on 5/25/76 and False on 12 before moving on.

  5. 5. Clarify Terminology

    If asked about circular numbers, say they are a different concept.

Pro Tip: dry-run 76 on paper once — it locks in why % 100 is the right mask for a 2-digit n.

Common Pitfalls

Mistakes that commonly break automorphic solutions.

  1. 1. Checking the Prefix Instead

    Asking whether n² starts with n is a different (wrong) problem.

    → Always compare the suffix / last k digits.

  2. 2. Wrong Power of Ten

    Using a fixed % 100 only works for 2-digit numbers.

    → Build the mask as 10 ** k from the digit count.

  3. 3. Counting Digits of n²

    k must be the length of n, not the length of the square.

    → Call len(str(n)) before squaring for the mask.

  4. 4. Confusing With Circular Numbers

    Different definitions; mixing them fails interviews.

    → Stick to “n² ends with n.”

  5. 5. Ignoring Overflow Stories

    In fixed-width languages, n*n may overflow before the suffix check.

    → In Python you are safe; mention care in C/Java interviews.

Edge Cases

Check these inputs before calling the solution done.

n <= 0

Return false

This tutorial uses positive integers only.

1, 5, 6

Single-digit hits

Common automorphic values — good smoke tests.

25 / 76

Golden tests

Must return true for any correct implementation.

12

Negative case

144 ends in 44 — must return false.

Large n

Big squares

Python ints stay exact; live preview is capped for speed.

Terminology

Not circular

Automorphic ≠ circular/cyclic number.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Base 10 classics. 5, 6, 25, and 76 are the examples most tutorials expect you to know.
  • Suffix property. Automorphic means n is a fixed point of squaring modulo 10^k.
  • Pairs. In base 10, automorphic numbers often come in complementary pairs for a given digit length.
  • Other bases. The same idea exists in other bases; interview prompts almost always mean base 10.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Verify the classics

  • Confirm 1, 5, 6, 25, 76
  • Reject 12, 15, 24

2. Count in a range

  • How many automorphic numbers are in 1…100?
  • Reuse is_automorphic

3. No str for digit count

  • Count digits with a divide-by-10 loop
  • Keep the modulus suffix check

4. Implement both styles

  • Write modulus and endswith versions
  • Assert they agree on a test set

Notes

  • Suffix, not prefix. Automorphic means n² ends with n — never confuse with starts-with checks.
  • k is the digit count of n; the mask is always 10 ** k.
  • Python handles large squares safely; fixed-width languages may need care.
  • State O(log n) time and O(1) extra space for the modulus method when asked.

Quick Takeaway: if the last k digits of n² equal n, the number is automorphic.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Single modulus checkO(log n)O(1)
String endswith checkO(log n)O(log n) for the strings
Range 1…UO(U log U)O(1)
Wrap Up

🎉 Conclusion

Automorphic numbers are a clean suffix exercise: count digits k, take (n * n) % (10 ** k), and compare with n. Master the modulus method first, then the string variant when you want shorter code.

Practice the three examples above, then continue to the average-of-N-numbers tutorial for a different classic interview warm-up.

Never check the prefix of n², never hard-code % 100 for every length, and always verify 25 and 76.

💡 Best Practices

✅ Do

  • Set k from the digit count of n
  • Use (n * n) % (10 ** k)
  • Guard n <= 0
  • Test 5, 25, 76, and 12
  • State O(log n) time when asked

❌ Don’t

  • Check whether n² starts with n
  • Hard-code a 2-digit modulus for all n
  • Count digits of the square for the mask
  • Confuse automorphic with circular
  • Skip overflow talk in fixed-width languages

Key Takeaways

Knowledge Unlocked

Five things to remember about automorphic numbers

Check square suffixes the interview-friendly way.

5
Core concepts
k 02

Digits

k = length of n

Math
% 03

Suffix

n² % 10^k

Code
76 04

Classic

76² = 5776

Example
O 05

Complexity

O(log n) time

Analysis

❓ Frequently Asked Questions

A positive integer n is automorphic if n squared ends with n. Example: 25^2 = 625, which ends with 25.
No. Automorphic checks the suffix of n^2. Circular/cyclic number concepts are different.
Some books include 0. In this tutorial, we focus on positive integers, so n <= 0 returns false.
Modulus gives the last k digits directly: n^2 % 10^k. That is exactly what we need to compare with n.
If k is number of digits, one check is O(k), and k is O(log n).
Loop through the range and call the same checker function for each number.
Yes. Convert n*n to a string and check if it ends with str(n). The modulus method is usually preferred in interviews.
In base 10, frequently cited examples include 1, 5, 6, 25, and 76.

Did you Know? 🔊

In base 10, 5, 6, 25, and 76 are common automorphic numbers because their squares end with the same digits.

Continue to Average of N Numbers

Learn how to compute the average of a list of numbers in Python.

Average tutorial →

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