Saturday, February 11, 2017

Write a Program in Java to show all Kaprekar number between 1 to 1000.

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 Kaprekar2
{
public static void main(String...alt)throws Exception
{
for(int i=1;i<=1000;i++)
{
long sqr1=i*i;
String sqr2=Long.toString(sqr1);
if(i<=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==i)
out.println(i);
}
}
}

Share this

0 Comment to "Write a Program in Java to show all Kaprekar number between 1 to 1000."

Post a Comment