Question
Print Kaprekar number in given range.
(A Kaprekar number is a number whose square when divided into two parts and such that the sum of parts is equal to the original number and none of the parts has value 0.)
ENTER A NUMBER: 45
45 IS A KAPREKAR NUMBER
45*45 = 2025 and 20 + 25 is 45
ENTER A NUMBER: 10
10 IS NOT A KAPREKAR NUMBER
10*10 = 100. It is not a Kaprekar number even if
sum of 100 + 0 is 100 because none of the parts should have value 0.
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class kaprekarNumberInGivenRange
{
public static void main()
{
int len=0,sum=0,firstPart=0,secondPart=0,i=0,lowerRange=0,upperRange=0;
String sq="";
Scanner sc=new Scanner(System.in);
System.out.print("ENTER A LOWER RANGE:");
lowerRange=sc.nextInt();
System.out.print("ENTER A UPPER RANGE:");
upperRange=sc.nextInt();
System.out.println("KAPREKAR NUMBERS:");
for(i=lowerRange;i<=upperRange;i++)
{
if(i<=3)
{
if(i==1)
{
System.out.print(i+" ");
}
}
else
{
sq=Integer.toString((i*i));
len=sq.length();
firstPart=Integer.parseInt(sq.substring(0,(len/2)));
secondPart=Integer.parseInt(sq.substring((len/2),len));
sum=firstPart+secondPart;
if(sum==i &&(firstPart!=0)&&(secondPart!=0))
{
System.out.print(i+" ");
}
}
}
}
}