Tuesday 27 October 2015

Java Program to check for 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");
}
}

No comments:

Post a Comment