Kaprekar Number in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds whether the given number is kaprekar number or not.

Take a number. Find the square of that number. Divide the number into two parts. If the sum of the two parts is equal to the original number, then the number is called kaprekar number.

Let's see the steps to solve the problem.

  • Initialise the n.
  • Find the square of the n.
  • Find the number of digits in the square of the n and store it in a variable.
  • Divide the square of n with 10, 100, 1000, etc.., until the digits count.
    • Check whether sum of any of those parts is equal to n or not.
  • Return True if they are equal else False.


Let's see the code.

 Live Demo

using namespace std;
bool isKaprekarNumber(int n) {
   if (n == 1) {
      return true;
   int nSquare = n * n, digitsCount = 0;
   while (nSquare) {
      nSquare /= 10;
   nSquare = n * n;
   for (int i = 1; i < digitsCount; i++) {
      int parts = pow(10, i);
      if (parts == n) {
      int sum = nSquare / parts + nSquare % parts;
      if (sum == n) {
         return true;
   return false;
int main() {
   int n = 25;
   string result = isKaprekarNumber(n) ? "True" : "False";
   cout << result << endl;
   return 0;


If you run the above code, then you will get the following result.



If you have any queries in the tutorial, mention them in the comment section.

Published on 09-Apr-2021 12:55:19