Array-promo

Question

Program to Check whether a given number is a Kaprekar number.
(A Kaprekar number is a number whose square when divided into two parts and such that 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 kaprekarNumber
{
    public static void main()
    {

        int num=0,len=0,sum=0,firstPart=0,secondPart=0;
        String sq="";
        Scanner sc=new Scanner(System.in);
        System.out.print("ENTER A NUMBER:");
        num=sc.nextInt();
        if(num<=3)
        {
            if(num==1)
            {
                System.out.println(num+" IS A KAPERKAR NUMBER");
            }
            else
            {
                System.out.println(num+" IS NOT A KAPREKAR NUMBER"); 
            }
        }
        else
        {
            sq=Integer.toString((num*num));
            len=sq.length();

            firstPart=Integer.parseInt(sq.substring(0,(len/2)));
            secondPart=Integer.parseInt(sq.substring((len/2),len));
            sum=firstPart+secondPart;

            if(sum==num &&(firstPart!=0)&&(secondPart!=0))
            {
                System.out.println(num+" IS A KAPERKAR NUMBER");

            }
            else
            {
                System.out.println(num+" IS NOT A KAPREKAR NUMBER");   
            }
        }

    }
}

				
			

Coding Store

Leave a Reply

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