# Finding out a Kaprekar number in Java

Hey guys! The topic for today is finding out **if a number is a Kaprekar number or not in Java**.

So what is a Kaprekar number?

## Kaprekar Number in Java

When you square a number, then split the number into two integers, sum those two integers and you end up with the same value you started with, then such a number is called as Kaprekar number.

**Explanation**

**Example 1:**

Consider a positive whole number: 45

Square the number: 45 x 45 = 2025

Split the squared number into two halves.

(i.e) 20 and 25.

Add these two halves and if we get the number we started with, then it is a Kaprekar number.

20 + 25 = 45.

Hence 45 is a *Kaprekar number*.

**Example 2:**

Consider a positive whole number: 4

Square the number: 4 x 4 = 16

Split the squared number into two halves.

(i.e) 1 and 6.

Add these two halves and if we get the number we started with, then it is a Kaprekar number.

1 + 6 = 7.

Hence 7 is a *Not a Kaprekar number*.

## Code for finding out if a number is Kaprekar number or not in Java

import java.util.*; class Kaprekar{ public static void main(String[]args) { Scanner scan = new Scanner(System.in); System.out.print("Enter the number: "); int number = scan.nextInt(); int square = number * number; // can use long for bigger numbers String squaredStr = Integer.toString(square); String left = "0"; String right = "0"; for(int i = 0; i < squaredStr.length() / 2; i++) { left = left + squaredStr.charAt(i); //storing the first half of string } for(int i = squaredStr.length() / 2; i < squaredStr.length(); i++) { right = right + squaredStr.charAt(i); //storing second half of string } int n1 = Integer.parseInt(left); int n2 = Integer.parseInt(right); if(n1 + n2 == number) { System.out.println(number + " is a Kaprekar Number!"); } else { System.out.println(number + " is not a Kaprekar Number."); } } }

**Output:**

Hope you understand the code ðŸ™‚

Any questions please feel free to drop in your comments.

You can also check out:

## Leave a Reply