Note: A positive number ‘n’ is squared that has ‘d’ number of digits and split into two pieces.
right-hand piece that has ‘r’ digits and a left-hand piece that has remaining ‘d-r=l’ digits.
If the sum of the two pieces(r+l) is equal to the number, then ‘n’ is a Kaprekar number.
The first few Kaprekar numbers are: 9, 45, 297 ......
Example 1: 9
Square of 9 = 9*9 = 81, right-hand piece of 81 = 1 and left hand piece of 81 = 8
Sum = 1 + 8 = 9, i.e. equal to the number. Hence, 9 is a Kaprekar number.
Example 2: 297
Square of 297 = 297*297 = 88209, right-hand piece of 88209 = 209 and left hand piece of 88209 = 88
Sum = 209 + 88 = 297, i.e. equal to the number. Hence, 297 is a Kaprekar number. */
import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Kaprekar
{
public static void main(String...alt)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
out.println("Enter a Number : ");
long n=Long.parseLong(br.readLine());
long sqr1=n*n;
String sqr2=Long.toString(sqr1);
if(n<=9)
sqr2="0"+sqr2;
int mid=sqr2.length()/2;
int left=Integer.parseInt(sqr2.substring(0,mid));
int right=Integer.parseInt(sqr2.substring(mid));
if(left+right==n)
out.println(n+" is Kaprekar No");
else
out.println(n+" is not Kaprekar No");
}
}
right-hand piece that has ‘r’ digits and a left-hand piece that has remaining ‘d-r=l’ digits.
If the sum of the two pieces(r+l) is equal to the number, then ‘n’ is a Kaprekar number.
The first few Kaprekar numbers are: 9, 45, 297 ......
Example 1: 9
Square of 9 = 9*9 = 81, right-hand piece of 81 = 1 and left hand piece of 81 = 8
Sum = 1 + 8 = 9, i.e. equal to the number. Hence, 9 is a Kaprekar number.
Example 2: 297
Square of 297 = 297*297 = 88209, right-hand piece of 88209 = 209 and left hand piece of 88209 = 88
Sum = 209 + 88 = 297, i.e. equal to the number. Hence, 297 is a Kaprekar number. */
import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Kaprekar
{
public static void main(String...alt)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
out.println("Enter a Number : ");
long n=Long.parseLong(br.readLine());
long sqr1=n*n;
String sqr2=Long.toString(sqr1);
if(n<=9)
sqr2="0"+sqr2;
int mid=sqr2.length()/2;
int left=Integer.parseInt(sqr2.substring(0,mid));
int right=Integer.parseInt(sqr2.substring(mid));
if(left+right==n)
out.println(n+" is Kaprekar No");
else
out.println(n+" is not Kaprekar No");
}
}
0 Comment to " Write a Program in Java to input a number and check whether it is a Kaprekar number or not."
Post a Comment