Home / Blue J / Java Program to check for a Kaprekar number

Java Program to check for a Kaprekar number

Here is given java program to check for a Kaprekar number.

But before what exactly is a Kaprekar number and why it is called a kaprekar number?

A Kaprekar number is a number whose square can be broken/partitioned in such a manner that the sum of the partitions adds up to bring the number itself.

Example: 992 = 9801 : 98+01 = 99  (hence a kaprekar number)

Why Kaprekar number. Kaprekar number is named after a great Indian Mathematician Kaprekar

DISCLAIMER:  This program is however limited to check until 99999 because int in java is of 4 bytes= (32 bits) i.e. range of -231 to +231 -1 (including 0) which makes: -2147483648 to +2147483647, Now since in this program 99999 2 exceeds the range for int so program is limited to produce kaprekar numbers until 99999.

import java.util.*;
class kaprekar
{

int digitcount(int x)
{
int digit=0;
	while(x!=0)
	{
	digit++;
	x/=10;
	}
return digit;
}

int return_A(int x)
{
	while(x%10==0)
	x/=10;
return x;
}

public static void main(String args[])
{
int n,A,B,sq,temp;
int digits;
Scanner sc=new Scanner(System.in);
kaprekar ob=new kaprekar();
System.out.print("Enter number : "); //  to check whether it is a Kaprekar number or not
n=sc.nextInt();
sq=n*n;
//count the number of digits in the square of that number
digits=ob.digitcount(n*n);

//now partition the square number using X=Ab^n + B ; where b=10 (decimal number system)
// partitioning theory is written above
A= sq/ (int)Math.pow(10,digits/2);	//But this will get Ab^n  so remove b^n:-
A=ob.return_A(A);
B= sq% (int)Math.pow(10,digits/2);

temp=A+B;
if(temp==n)
System.out.print("\nIt is a Kaprekar number \n");
else
System.out.print("\n Not a kaprekar number");
}
}

OUTPUT:

c program for kaprekar number
Kaprekar number(Output-1)
program for kaprekar number
Kaprekar Number(Output-2)

Incoming terms:  Java program for Kaprekar number icse class 10 class 12, Java program to check for a kaprekar number

Check Also

Program to check Upper Triangular matrix

What is Upper Triangular Matrix?  An upper triangular matrix is a square matrix in which ...

One comment

  1. KAISER SOURIN CHAKRABORTY

    IT WAS HELPFUL but level is quite high

Leave a Reply

Your email address will not be published. Required fields are marked *

Preventing spam * Time limit is exhausted. Please reload the CAPTCHA.