Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C Program to Find an Automorphic Number
In C, an automorphic number is a positive integer whose square ends with the number itself. For example, 52 = 25 (ends with 5), and 252 = 625 (ends with 25). This article demonstrates how to check whether a given number is automorphic in C programming.
Syntax
int isAutomorphicNumber(int num);
Examples of Automorphic Numbers
Consider the following examples to understand automorphic numbers
- 5: 52 = 25 (ends with 5) Automorphic
- 25: 252 = 625 (ends with 25) Automorphic
- 7: 72 = 49 (ends with 49, not 7) Not Automorphic
Method 1: Iterative Digit Comparison
This approach compares the last digits of the number and its square iteratively using division and modulo operations
#include <stdio.h>
int isAutomorphicNumber(int num) {
int square = num * num;
while (num > 0) {
if (num % 10 != square % 10) {
return 0; // Not automorphic
}
num /= 10;
square /= 10;
}
return 1; // Automorphic
}
int main() {
int number = 25;
printf("Number: %d<br>", number);
printf("Square: %d<br>", number * number);
if (isAutomorphicNumber(number)) {
printf("%d is an Automorphic Number<br>", number);
} else {
printf("%d is not an Automorphic Number<br>", number);
}
return 0;
}
Number: 25 Square: 625 25 is an Automorphic Number
Method 2: Mathematical Modulo Approach
This approach counts the digits in the number and uses the modulo operation with 10d to extract the last d digits from the square
#include <stdio.h>
int countDigits(int num) {
int count = 0;
while (num > 0) {
count++;
num /= 10;
}
return count;
}
int power(int base, int exp) {
int result = 1;
for (int i = 0; i < exp; i++) {
result *= base;
}
return result;
}
int isAutomorphicNumber(int num) {
int square = num * num;
int digits = countDigits(num);
int divisor = power(10, digits);
return (square % divisor == num);
}
int main() {
int number = 5;
printf("Number: %d<br>", number);
printf("Square: %d<br>", number * number);
if (isAutomorphicNumber(number)) {
printf("%d is an Automorphic Number<br>", number);
} else {
printf("%d is not an Automorphic Number<br>", number);
}
return 0;
}
Number: 5 Square: 25 5 is an Automorphic Number
Comparison
| Method | Time Complexity | Space Complexity | Advantage |
|---|---|---|---|
| Iterative | O(d) | O(1) | Simple logic, no helper functions |
| Modulo | O(d) | O(1) | Direct mathematical approach |
Conclusion
Both methods effectively determine automorphic numbers with O(d) time complexity, where d is the number of digits. The iterative approach is simpler while the modulo approach provides a more mathematical solution.
