Adam Number in C++

C++Server Side ProgrammingProgramming

In this section we will see how to write a program that can check whether a given number is Adam number or not. Before diving into code let us see what is the Adam number?

The Adam number is a number say n, then if the square of n and square of the reverse of n are reverse of each other, then the number is Adam number. For an example let us consider a number 13. The reverse is 31. Then square of 13 is 169, and square of 31 is 961. The 169 and 961 are reverse of each other so the number 13 is an Adam number.

Steps to check whether given number is Adam number of not −

  • Take the number n
  • Reverse the number and store into m
  • Get Square of n and store it into sq_n
  • Get Square of m and store it into sq_m
  • Check whether sq_n and reverse of sq_m are same or not.

Example

 Live Demo

#include<iostream>
using namespace std;
int reverseNumber(int num) {
   int res = 0;
   while(num != 0) {
      res = res * 10 + num % 10; //cut last digit and add into the result
      num /= 10; //reduce the number
   }
   return res;
}
bool checkAdamNumber(int num) {
   int rev_num = reverseNumber(num);
   //get the square of the number and the reverse number
   int sq_num = num * num;
   int sq_rev_num = rev_num * rev_num;
   //if the sq_num and sq_rev_num are reverse of each other, then they are Adam Number.
   if(sq_num == reverseNumber(sq_rev_num)) {
      return true;
   }
   return false;
}
main() {
   int num;
   cout << "Enter a number to check whether it is Adam number or not:";
   cin << num;
   if(checkAdamNumber(num)) {
      cout << "The number is an Adam number";
   } else {
      cout << "The number is not an Adam number";
   }
}

Output

Enter a number to check whether it is Adam number or not:13
The number is an Adam number

Output

Enter a number to check whether it is Adam number or not:25
The number is not an Adam number
raja
Published on 24-Jul-2019 12:44:57
Advertisements