How to check number is kaprekar number java example

Kaprekar number is the number whose square in that base can be split into two parts that add up to the original number.
To find the Kaprekar number we need to follow 3 steps
1. First take the square of the number
2. Get the middle point of that digit and split it into two.
3.Then take the total of the two digits and check with the original number, if they are equal then it is a Kaprekar Number.
e.g. Suppose user has entered number as 9, take the square of that number which is 81 if we split this into two parts then 8 and 1. But the total of 8 and 1 is 9 , so the number is Kaprekar number

Java example to test Kaprekar Number

In following example, we are accepting the user entered number and testing that number whether it is Kaprekar number or not.
1. First we are taking square of it.
2. Then we are converting it from int to String.
3 Find the length of the String
4. Take mid point of the String and split it in two parts.
5 Converting the parts to int again.
6. Checking total of these number is same as original number. If it is same then it is a Kaprekar number and if it is different then it is not Kaprekar number.

class KaprekarTest
public static void main(String[] args) throws IOException
BufferedReader br=new BufferedReader(new InputStreamReader(;
System.out.print("Enter a Number to check for Kaprekar Number : ");
int numberToTest=Integer.parseInt(br.readLine()); //Get the input from user
int squareOfNum = numberToTest*numberToTest; // Our first step is to find square of the number
String squareStr=Integer.toString(squareOfNum); //converting the square into a String to get mid point
if(squareOfNum <= 9)
int lengthOfDigit = squareStr.length(); //Finding length of the String
int mid= lengthOfDigit/2; //finding the middle point to check Kaprekar number
String leftDigitsStr=squareStr.substring(0,mid); //taking out digits from left side of the square
String rightDigitsStr=squareStr.substring(mid); //taking out digits from right side of the square
int leftDigit=Integer.parseInt(leftDigitsStr); //converting the left side String into Integer
int rightDigit=Integer.parseInt(rightDigitsStr); //converting the right side String into Integer
if( leftDigit+rightDigit == numberToTest ) //Check for Kaprekar number
System.out.println(numberToTest+" is a Kaprekar Number");
System.out.println(numberToTest+" is Not a Kaprekar Number");
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment