Time Limit: 2s Memory Limit: 192MB
Problem Description
An automorphic number is a number whose square ends with the number itself.
For example:
25^2=625
76^2=5776
9376^2=87909376
Find all automorphic numbers less than or equal to 200000.
Input Format
No input
Output Format
All automorphic numbers less than or equal to 200000 (including 0, numbers separated by two spaces, no trailing space)
Sample Input
No input
Sample Output
0 1 5 6 25 76 376 625 9376 90625 109376
Code
#include <iostream>#include <vector>#include <cmath>using namespace std;
// Function: Check if a number is automorphic
bool isAutomorphic(long long n) { if (n == 0 || n == 1) return true;
long long square = n * n; long long temp = n; long long divisor = 1;
// Calculate the number of digits in n to determine the number of digits to compare
while (temp > 0) { divisor *= 10; temp /= 10; }
// Compare if the last digits of the square equal the original number
return (square % divisor) == n;}
int main() { vector<long long> results;
// Check all numbers from 0 to 200000
for (long long i = 0; i <= 200000; i++) { if (isAutomorphic(i)) { results.push_back(i); } }
// Output results, numbers separated by two spaces
for (int i = 0; i < results.size(); i++) { if (i > 0) { cout << " "; } cout << results[i]; }
return 0;}
Output Result
Problem Analysis
An automorphic number is a number whose square ends with the number itself. For example:
-
5² = 25, the last digit is 5
-
25² = 625, the last digits are 25
-
76² = 5776, the last digits are 76
We need to find all automorphic numbers less than or equal to 200000.
Methodology
-
Check for Automorphic Numbers: For a number n, calculate n², then check if the last digits of n² equal n.
-
Get the Number of Digits: Based on the number of digits in n, take the corresponding last digits of n² for comparison.
-
Iterate Through All Numbers: Iterate from 0 to 200000, checking each number to see if it is automorphic.
Code Explanation
-
Automorphic Number Check Function:
<span>isAutomorphic</span>function:
-
Calculate the square of n
-
Calculate the number of digits in n to determine the number of digits to compare
-
Check if the last digits of the square equal the original number n
Main Function:
-
Create a vector to store results
-
Iterate through all numbers from 0 to 200000, checking if they are automorphic
-
Output results in the specified format (numbers separated by two spaces)

C++ Basic Tutorial Collection
C++ Basic Resources
1. C++ Output
2. C++ Variables
3. C++ Input
4. C++ Expressions
5. IF Statements
6. IF Applications
7. WHILE Loops
8. FOR Loops
9. Arrays
10. One-Dimensional Arrays
11. Two-Dimensional Arrays
12. C++ Functions
13. C++ File Operations – Writing Files
If you find it useful, please click on me



