← All resources

Java program on Kaprekar Number

Kaprekar Number

In mathematics, a non-negative integer is called a “Kaprekar number” if its square can be split into two parts that add up to the original number. For instance, 45 is a Kaprekar number, because 452 = 2025 and 20 + 25 = 45. Kaprekar numbers are named after D. R. Kaprekar.

Ex:

9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777

import java.util.*;
public class Kaprekar
{
    public static void main()
    {
        Scanner sc = new Scanner(System.in);
        int n, c=0, n2, sq, pow;
        System.out.print("Enter the number: ");
        n = sc.nextInt();       //Taking input
        n2 = n;                 //Initialising copy
        sq = n*n;               //Storing square
        while(n>0)
        {
            n = n/10;           //Counting the number of digits
            c++;
        }
        pow = (int)Math.pow(10, c); //Type casting
        /*sq%pow gives the last c digits from the end of a square 
        where as sq/pow returns the starting digits*/
        if(sq%pow + sq/pow == n2)        
            System.out.println("The number is a Kaprekar number");
        else
            System.out.println("The number is not a Kaprekar number");
    }
}
/*Type casting is the process of converting a value of a higher datatype to a value of lower data type.
This results in a loss of data therefore is not automatically allowed by Java.

ex:

double x = 2.3;
int y = x;  -->This will give a compile time error as double is a higher order data type as compared to int

therefore:

int y = (int)x;
Order of data types:
byte
short
char
int
long
float
double
String
 */

Output

program on Automorphic Number – click here