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.

import java.io.*;

class KaprekarTest

{

public static void main(String[] args) throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

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)

squareStr="0"+squareStr;

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");

else

System.out.println(numberToTest+" is Not a Kaprekar Number");

}

}

## 0 comments:

## Post a Comment