Kaprekar Number in Java

A detailed explanation of Kaprekar Numbers in Java with examples, logic breakdown, and a complete Java implementation. This article also includes beginner-friendly practice challenges to help you strengthen number-system and loop-based problem-solving skills.

Kaprekar Number in Java

A Kaprekar Number is a special type of number that, when squared, can be split into two parts which add up to the original number. This concept is widely used in coding interviews and mathematical programming problems, making it important for beginners and intermediates to understand.

What Is a Kaprekar Number?

A number N is called a Kaprekar Number if:

N² = left_part + right_part = N

The right part must have the same number of digits as the original number, but the left part can be empty (treated as 0).

Example

Let's take the number 45.

  • 45² = 2025
  • Split into two parts → 20 and 25
  • 20 + 25 = 45

Since the sum equals the original number, 45 is a Kaprekar Number.

Steps to Check a Kaprekar Number

  1. Read the input number.
  2. Calculate its square.
  3. Convert the square into a string.
  4. Split the string into two parts:
    • Right part: same length as the original number
    • Left part: remaining digits
  5. If missing, treat the left part as 0.
  6. Add both parts.
  7. If the sum equals the original number → it is a Kaprekar Number.

Java Program to Check Kaprekar Number


import java.util.*;

public class KaprekarNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        if (isKaprekar(num)) {
            System.out.println(num + " is a Kaprekar Number.");
        } else {
            System.out.println(num + " is NOT a Kaprekar Number.");
        }

        sc.close();
    }

    public static boolean isKaprekar(int num) {
        if (num == 1) return true;

        long square = (long) num * num;
        String s = Long.toString(square);
        int len = s.length();
        int digits = Integer.toString(num).length();

        String right = s.substring(len - digits);
        String left = (len - digits <= 0) ? "0" : s.substring(0, len - digits);

        int leftNum = Integer.parseInt(left);
        int rightNum = Integer.parseInt(right);

        return (leftNum + rightNum) == num;
    }
}

  

Output

Enter a number: 45
45 is a Kaprekar Number.
  

Practice Challenges

Test your understanding with these challenges:

  • Modify the program to display all Kaprekar Numbers between 1 and 1000.
  • Create a function that counts how many Kaprekar Numbers exist in a given range.
  • Write a program to find the next Kaprekar Number for a given input.

Understanding Kaprekar Numbers helps build confidence in mathematical programming, digit manipulation, and string-based logic — all essential areas for Java interviews.