The Program in C++ Program to Check If given number is a Kaprekar number or not is given below:
#include <iostream>
#include <cmath>
using namespace std;
bool isKaprekar(int num) {
// Check for the base case
if (num == 1) return true;
// Calculate the square of the number
int square = pow(num, 2);
int digits = log10(num) + 1;
// Split the square into two parts
for (int i = 1; i < digits; i++) {
int right = square % (int) pow(10, i);
int left = square / (int) pow(10, i);
// Check if the sum of left and right parts is equal to the original number
if (left + right == num) return true;
}
return false;
}
int main() {
int num;
cout << "Hello Codeauri Family,enter a number here to check if it is Kaprekar Number or Not!:\n ";
cin >> num;
if (isKaprekar(num))
cout << num << " is a Kaprekar number" << endl;
else
cout << num << " is not a Kaprekar number" << endl;
return 0;
}
Output:
Hello Codeauri Family,enter a number here to check if it is Kaprekar Number or Not!:
4950
4950 is not a Kaprekar number
Pro-Tips💡
This program uses a function isKaprekar
that takes an integer as input and returns a boolean indicating whether the number is a Kaprekar number or not.
The function first checks for the base case (i.e., the number is 1), then calculates the square of the number, and
finally splits the square into two parts and checks if the sum of the two parts is equal to the original number.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.