# Kaprekar Number in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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.

## Example

Let's see the code.

Live Demo

#include<bits/stdc++.h>
using namespace std;
bool isKaprekarNumber(int n) {
if (n == 1) {
return true;
}
int nSquare = n * n, digitsCount = 0;
while (nSquare) {
digitsCount++;
nSquare /= 10;
}
nSquare = n * n;
for (int i = 1; i < digitsCount; i++) {
int parts = pow(10, i);
if (parts == n) {
continue;
}
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;
}

## Output

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

False

## Conclusion

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