Automorphic Number in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
int main() {
    int n, sq;
    scanf("%d", &n);
    sq = n * n;
    while(n > 0) {
        if(n % 10 != sq % 10) {
            printf("Not Automorphic");
            return 0;
        }
        n /= 10;
        sq /= 10;
    }
    printf("Automorphic");
}

C Output

Input:
25

Output:
Automorphic


C++ Program

#include <iostream>
using namespace std;
int main() {
    int n;
    cin >> n;
    long sq = n * n;
    while(n > 0) {
        if(n % 10 != sq % 10) {
            cout << "Not Automorphic";
            return 0;
        }
        n /= 10;
        sq /= 10;
    }
    cout << "Automorphic";
}

C++ Output

Input:
76

Output:
Automorphic


JAVA Program

import java.util.*;
class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long sq = (long) n * n;
        while(n > 0) {
            if(n % 10 != sq % 10) {
                System.out.println("Not Automorphic");
                return;
            }
            n /= 10;
            sq /= 10;
        }
        System.out.println("Automorphic");
    }
}

JAVA Output

Input:
7

Output:
Not Automorphic


Python Program

n = int(input())
sq = n * n
while n > 0:
    if n % 10 != sq % 10:
        print("Not Automorphic")
        break
    n //= 10
    sq //= 10
else:
    print("Automorphic")

Python Output

Input:
6

Output:
Automorphic


In-Depth Learning – Entire Concept in Paragraphs

What It Really Means
An automorphic number is a non-negative integer whose square ends with the same digits as the number itself. If the number has dd digits, “ends with” means the last dd digits of n2n^2 match nn exactly. In notation, this is n2n(mod10d)n^2 \equiv n \pmod{10^d}. That congruence is the clean mathematical translation of the suffix idea: if two numbers differ by a multiple of 10d10^d, then they share the last dd digits, which is why the test “compare digits from the right” is equivalent to the modular test “reduce by 10d10^d”.

Example
Take n=25n=25. Its square is 625625. Since 25 has two digits, you compare the last two digits of 625625 with 2525—a perfect match, so 25 is automorphic. Try n=76n=76: 762=577676^2=5776. Here you compare the last two digits of 57765776 with 7676; again a match. For a three-digit example, n=376n=376: 3762=141,376376^2=141{,}376; the last three digits are 376, so it qualifies. For n=7n=7, 72=497^2=49 and the last digit is 9, not 7, so 7 is not automorphic. Notice that 0 and 1 also trivially satisfy the definition: 02=00^2=0 and 12=11^2=1.

Real-Life Analogy
Imagine stamping a product code onto boxes. Your quality check says: “When I double-stamp the code (simulate squaring), the last dd characters on the second imprint must still read exactly the original dd-character code.” If the second imprint still ends with the original code, it passes as “automorphic”—it preserves its identity at the tail under a specific transformation.

Why the Modular View Matters
Switching from “compare last digits” to the congruence n2n(mod10d)n^2 \equiv n \pmod{10^d} unlocks better implementations and deeper math. In code, instead of squaring a potentially large integer and then converting to a string or peeling digits, you can take m=10dm=10^d and compute (nmodm)2modm(n \bmod m)^2 \bmod m safely in 64-bit (or with big integers when needed). This reduces overflow risk and keeps the logic purely arithmetic. Conceptually, it positions automorphic numbers as idempotent elements modulo 10d10^d (numbers xx where x2xx^2 \equiv x), connecting a cute digit puzzle to a classic ring-theory idea.

How to Check Without Overflow
If nn might be big for your language’s integer type, compute d=number of digits of nd=\text{number of digits of }n and set m=10dm=10^d. Reduce nn to r=nmodmr=n \bmod m (which is just nn itself if dd is the digit count), then compute t=(rr)modmt=(r \cdot r) \bmod m using modular multiplication (each multiply followed by a mod). If t=rt=r, it’s automorphic. This avoids forming the full square in a fixed-width type. It’s the same logic as the digit-by-digit loop that divides nn and n2n^2 by 10 in tandem from right to left; modular arithmetic just wraps that thought in one neat step.

The Curious Pattern of Endings
In base 10, the one-digit automorphic residues are 0, 1, 5, and 6, because 02=00^2=0, 12=11^2=1, 52=255^2=25 ends with 5, and 62=366^2=36 ends with 6. As you demand more ending digits, only four “families” keep surviving: endings that are all zeros (…000), all ones (…001), and the two classic nontrivial tails that keep growing: …625 and …376. That’s why the famous finite examples you see often are 2562525 \leftrightarrow 625 and 7637693769062589062576 \leftrightarrow 376 \leftrightarrow 9376 \leftrightarrow 90625 \leftrightarrow 890625 \ldots Each step means “add one more leading digit so that squaring still preserves the suffix,” and it’s always possible to extend these tails by exactly one choice for the new leading digit. If you square 625 you get 390625 (ends with 0625); square 9376 you get 87,890, ̄– actually 9,376² = 87, ̄ (the exact middle digits don’t matter), and the result ends with 9376. These two infinite tails are not coincidence—they’re consequences of how 10 factors as 2×52 \times 5 and of how idempotents combine in modular arithmetic.

A Peek Under the Hood (Chinese Remainder Theorem Intuition)
Because 10=2510=2 \cdot 5, working modulo 10d10^d is the same as working simultaneously modulo 2d2^d and modulo 5d5^d. The idempotents modulo a prime power pdp^d are just 0 and 1, so modulo 2d2^d you can be 0 or 1, and modulo 5d5^d you can be 0 or 1. By the Chinese Remainder Theorem, those choices pair up to give four idempotents modulo 10d10^d. When you translate those four back into decimal endings, you get the families corresponding to endings with all zeros, all ones, and the two nontrivial tails that stabilize as …625 and …376. That’s why there are exactly four residue classes of automorphic endings for any fixed length dd. Among ordinary base-10 integers, that theory manifests as the familiar 0, 1, 5, 6 for one digit, 00, 01, 25, 76 for two digits, 000, 001, 625, 376 for three digits, 0000, 0001, 0625, 9376 for four digits, and so on.

Building Longer Automorphic Numbers Digit by Digit
There’s a constructive way to “grow” automorphic numbers. Suppose you already have a kk-digit tail aka_k with ak2ak(mod10k)a_k^2 \equiv a_k \pmod{10^k}. You seek a (k+1)(k+1)-digit extension ak+1=b10k+aka_{k+1} = b \cdot 10^k + a_k such that ak+12ak+1(mod10k+1)a_{k+1}^2 \equiv a_{k+1} \pmod{10^{k+1}}. Expand ak+12a_{k+1}^2 and reduce modulo 10k+110^{k+1}; because 10kak10^k \cdot a_k is a multiple of 10k10^k, only a small linear condition in bb survives. Solving that congruence produces exactly one digit b{0,,9}b \in \{0,\dots,9\} that works. Repeating this “Hensel-style lift” yields the infinite tails ending in …625 and …376, and it explains why each level has a unique extension.

Choosing an Implementation Strategy
You can check automorphism in three equivalent ways: string suffix, digit-by-digit arithmetic, or modular arithmetic. The string way converts n2n^2 and asks if its decimal form ends with the decimal string for nn; it’s easy to read and great for teaching, but you still risk huge strings if nn is massive. The digit-loop you already used is pure integer math and stable: peel the last digit of nn and n2n^2 simultaneously and compare, stopping as soon as a mismatch appears; its cost is proportional to the number of digits. The modular method is the cleanest mathematically and avoids squaring beyond what the modulus can hold; compute m=10dm=10^d and test ((nmodm)(nmodm))modm==(nmodm)((n \bmod m)\cdot(n \bmod m)) \bmod m == (n \bmod m). For interview answers, explain all three and pick one that matches the constraints.

Handling Edge Cases
Zero and one are automorphic by definition; very small negatives are usually excluded because “ends with” is defined for non-negative integers in base 10, but if you take absolute values then (n)2=n2(-n)^2 = n^2 so the status would match the positive counterpart. Extremely large inputs in fixed-width languages can overflow on the square, so the modular approach or big-integer libraries are safer. Also note that leading zeros don’t count; when we say a number “ends with 0625,” we mean a larger number whose actual last four digits are 0625 (like 90625), not that we’re padding with zeros on the left of the original number.

Complexity and Practical Performance
The digit-by-digit comparison runs in O(d)O(d) time for dd digits and constant space, and often short-circuits early on mismatches. The modular test also runs in O(d)O(d) if you count the cost of multiplying dd-digit numbers, but with machine integers under a fixed modulus it’s effectively O(1)O(1). If you do the naive square then string suffix, you also pay O(d)O(d) for conversion and comparison. For repeated queries over many values, precomputing nothing special is usually fine because the per-check cost is tiny; if you were generating all automorphic numbers up to some bound, the constructive growth method is more interesting than brute-force scanning.

Where It Shows Up in the Wild
Pure automorphic checks rarely appear in production features, yet the mechanics behind them are everywhere. Suffix tests are central in parsing and protocol design, modular arithmetic drives hashing, checksums, cryptographic primitives, and error-detecting codes, and Chinese Remainder Theorem reasoning underlies multi-modulus optimizations in big-integer libraries. Practicing with automorphic numbers gives you a compact playground to exercise those same mental muscles you’ll use when validating numeric encodings, building fast modular routines, or designing suffix-matching logic in text and binary data.

Interview-Ready Insights
If asked to code this, explain the definition succinctly, state the congruence n2n(mod10d)n^2 \equiv n \pmod{10^d}, and pick an implementation that respects integer limits. Mention that 0, 1, 5, 6 are the single-digit automorphic residues and that longer tails stabilize to the two infinite patterns ending in …625 and …376. Be prepared to discuss overflow, to switch to modulo logic, and to outline how CRT explains the count of solutions. If asked to “generate the next automorphic with one more digit,” sketch the lifting step that solves for exactly one new leading digit each time.

Real-World Analogy (Another Angle)
Think of applying a “company seal” twice to a document. The policy says the second stamp’s last few characters must still reveal the original seal text precisely. Only special seals survive this duplication unchanged at the tail; automorphic numbers are those special seals in base-10 arithmetic, resistant to that particular transformation.

SEO-Optimized Closing Paragraph
Understanding automorphic numbers—integers whose squares end with the same digits—builds powerful intuition for modular arithmetic, suffix matching, and number-theory ideas like idempotence and the Chinese Remainder Theorem. By mastering both the simple digit-by-digit method and the robust modulus test n2n(mod10d)n^2 \equiv n \pmod{10^d}, beginners learn how to design overflow-safe checks, reason about time complexity, and explain elegant patterns such as the infinite tails …625 and …376. This knowledge pays off in coding interviews, competitive programming, and real projects that rely on base conversions, hashing, checksum logic, and exact integer computations, making automorphic numbers a memorable, practical bridge between playful math puzzles and real-world software engineering.