Find Automorphic Number in C Program

C


Problem Description

We are given a number and we have to check whether it is an automorphic number or not. An Automorphic Number is a number whose square ends with the number itself. For example, 52 = 25 (ends with 5), so 5 is an Automorphic Number. In this article, we will learn how to check whether a given number is an automorphic number or not in C.

Examples

Consider the following examples, which will help you understand how to find an Automorphic Number:

Example 1

Input:
25

Output:
True

Explanation:
Number = 25
Now, calculate 25² = 625.
It is Automorphic.

Example 2

Input:
7

Output:
False

Explanation:
Given Number: 7
Now, calculate the square: 7² = 49.

Approaches to find if a number is an Automorphic number or not in C

To solve this problem, here are the two approaches that you can use:

Iterative Method

This is a simple and direct approach. In this approach, we compute the square of N. Then, we compare the last digits of the square and number iteratively using division and modulo operations. We stop when all the digits of the number are compared.

Implementation Code

#include<stdio.h>

int isAutomorphicNumber(int num) {
    int square = num * num;

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

int main() {
    int number = 5;

    if (isAutomorphicNumber(number)) {
        printf("%d is an Automorphic Number
", number); } else { printf("%d is not an Automorphic Number
", number); } return 0; }

Output:

5 is an Automorphic Number

Time Complexity:

O(d)

Space Complexity:

O(1)

Mathematical Modulo Approach

In this approach, we first count the number of digits in the number. Then, we calculate 10d, where d is the number of digits in the number. Now, we find the square of the number and use the modulo operation square mod 10d. If the result matches the number, then the input number is automorphic.

Implementation Code

#include<stdio.h>
#include<math.h>

int isAutomorphicNumber(int num) {
    int square = num * num;
    int digits = log10(num) + 1;

    if (square % (int)pow(10, digits) == num) {
        return 1;
    }
    return 0;
}

int main() {
    int num = 5;

    if (isAutomorphicNumber(num)) {
        printf("%d is an Automorphic Number.
", num); } else { printf("%d is not an Automorphic Number.
", num); } return 0; }

Output:

5 is an Automorphic Number.

Time Complexity:

O(d)

Space Complexity:

O(1)

Updated on: 2025-01-06T19:01:50+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements