Java Program to Check Kaprekar Number

In the previous article, we have discussed Java program to Check Deficient Number

In this article we are going to understand what Kaprekar number is and how we can check whether a number is Kaprekar or not in Java with examples.

Program to Check Kaprekar Number

Kaprekar numbers are numbers whose square can be divided into two parts which when added result in the original number.

Example :

  • 45: 452=2025; 20+25=45 Kaprekar Number
  • 40: 402= 1600; 16+00=16 Not Kaprekar Number
  • 9: 92 = 81; 8+1=9 Kaprekar Number

In the above examples the numbers 9 and 45 are Kaprekar numbers as sum of the halves of their squares adds up to the number itself. However 40 is not a Kaprekar number.

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Approach :

  1. We ask the user to enter/declare a number and store it .
  2. We square the number and then divide the digits into two parts. Then the two parts are added together.
  3. If the sum is the same as the entered number, then the number is said to be a Kaprekar number.

Program:

import java.util.Scanner;

public class KaprekarNumber
{
    public static void main(String args[])
    {
        //Taking the number as input from the user using scanner class
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a number : ");
        int num = scan.nextInt();

        if(iskaprekar(num))
        {
            System.out.println(num+" is a Kaprekar number");
        }
        else
        {
            System.out.println(num+" is Not a Kaprekar number");
        }
    }

    //method to check Kaprekar Number
    static boolean iskaprekar(int num)
    {
        // 1 is a Kaprekar number
        if (num == 1)
            return true;

        int squareNum = num * num;
        int count = 0;
        // Counting number of digits
        while (squareNum != 0)
        {
            count++;
            squareNum /= 10;
        }
    
        squareNum = num*num;
        for (int iter=1; iter<count; iter++)
        {
             // This avoids the number like 10, 100, 1000 as none of them are Kaprekar number
            int part = (int) Math.pow(10, iter);
            if (part == num)
                continue;
    
             //Adds both the halves
            int sum = squareNum/part + squareNum % part;
            //Checks whether both numbers are equal
            if (sum == num)
                return true;
        }
    
        return false;
    }
}
Output:

Case-1

Enter a number : 9
9 is a Kaprekar number

Case-2

Enter a number : 8
8 is a Kaprekar number

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Related Java Programs: