Java Program to check Kaprekar number

Java Program to check Kaprekar number

Question. Write a Java Program to check Kaprekar number.
Kaprekar number are those number whose square, if split into parts and then add it, will be the same as the original number. It is named after Dattaraya Ramchandra Kaprekar was an Indian.
Say 45, If we square it we get 2025 that is 452 = 2025, and split it as 20 and 25 then add it, will get 45.

452 = 2025 then 20 + 25 = 45.

Java program as follows

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
public class KaprekarNum{

    // main method begins execution of this class
    public static void main(String args[]) throws IOException
    {

        int square, temp, counter = 0, reminder, quotient;
        int n;   // The number to find Kaprekar Number

        InputStreamReader input = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(input);
        System.out.print("Enter a number to check Kaprekar number: ");
        // Waiting for the user input
        n = Integer.parseInt(br.readLine()); // say 45
        temp = n;            // Store n into temp variable
        square = n * n;    // Square of 45 is 2025
        // find total number of digits
        while (n != 0) {
            counter++;
            n = n / 10;
        }
        // reminder for 2025 % 100 will be 25
        reminder = square % ((int) Math.pow(10, counter));
        // quotient for 2025 / 100 will be 20
        quotient = square / ((int) Math.pow(10, counter));
        /* checking the Kaprekar number after adding of reminder and quotient
           with the original number */
        if ((reminder + quotient) == temp)
        {
            System.out.println(temp + " is a kaprekar number ");
        } else
        {
            System.out.println(temp + " is not a kaprekar number ");
        }

    } // end method main
} // end class

Output
Enter a number to check Kaprekar number: 45
45 is a kaprekar number

Enter a number to check Kaprekar number: 44
44 is not a kaprekar number


SHARE THIS
Previous Post
Next Post