Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximize number of continuous Automorphic numbers in C++
Given the task is to maximize the number of continuous Automorphic elements in a given array with N number of elements.
An automorphic number is a number whose square ends with the same digits as the number itself. For example 5 is an automorphic number as 5*5 = 25 and 25 ends with 5.
Let’s now understand what we have to do using an example −
Input − arr[]={5,3,625,6,8,1}
Output − 2
Explanation − Automorphic numbers present in the above array are 5, 625, 6 and 1 but the maximum continuous automorphic numbers are {625,6} which makes the output = 2.
Input − arr[]={33, 25, 1, 76, 4}
Output − 3
Approach used in the below program as follows
In main() function create a variable ‘n’ of type int and store in it, the size of given array.
In function MaxAutomorphic initialize CurrentMax=0 and Maximum=0 both of type int to store the current maximum value and maximum value so far respectively.
Loop from i=0 till i<n and check if given number is automorphic or not by calling the IsAutomorphic() function.
In the IsAutomophic() function initialize a variable sqr= n*n of type int to store the square of number n
Loop using the while loop with condition n>0 and compare the last digits of n and sqr to check if the number is automorphic or not.
Back into the MaxAutomorphic() function, if number is not automorphic then set CurrentMax=0
Else, if the number is found to be automorphic then add 1 to CurrentMax and store the greater number out of CurrentMax and Maximum into the Maximum variable.
Example
#include <bits/stdc++.h>
using namespace std;
//Function to check if number is automorphic
bool IsAutomorphic(int n){
//Storing the square of n
int sqr = n * n;
//Comparing the digits
while (n > 0){
/*Return false if any digit of n doesn't
match with its square's last digits*/
if (n % 10 != sqr % 10)
return false;
n /= 10;
sqr /= 10;
}
return true;
}
int MaxAutomorphic(int arr[], int size){
int CurrentMax = 0, Maximum = 0;
for (int i = 0; i < size; i++){
//Checking if the element is non-automorphic
if (IsAutomorphic(arr[i]) == false)
CurrentMax = 0;
//Updating CurrentMax and Maximum if number is automorphic
else{
CurrentMax++;
Maximum = max(CurrentMax, Maximum);
}
}
return Maximum;
}
//Main function
int main(){
int arr[] = { 33, 25, 1, 76, 4 };
int size = sizeof(arr) / sizeof(arr[0]);
cout << MaxAutomorphic(arr, size);
return 0;
}
Output
If we run the above code we will get the following output −
3