Kaprekar Number in JAVA

Kaprekar Number in JAVA

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.

  • Consider an n-digit number k.
  • Square it and add the right n digits of the square to the left n or n-1 digits.
  • If the resultant sum is equal to the number k, then k is called a Kaprekar Number.

For Example :-
Input         : 9
Square      : 81
Sum          : 8 + 1 = 9
Output      : It is a Kaprekar Number  
 
Input         : 297
Square      : 88209
Sum          : 88 + 209 = 297
Output      : It is a Kaprekar Number 

Input         : 10
Square      : 100
Sum          : 1 + 00 = 1
Output      : It is not a Kaprekar Number 

 


Program to check & print whether a number is Kaprekar number or not :-


Program :-

import java.io.*;
import java.util.*;
class Kaprekar
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        long n,sq,p,c,pow,x,y,sum;
        double dig=0;
        System.out.println("Enter Number");
        n= in.nextInt();
        sq= n*n;
        p=sq;
        while(sq>0)
        {
            sq=sq/10;
            dig++;
        }
        c = (int) Math.ceil(dig/2);
        pow = (int) Math.pow(10,c);
        x = p%pow;
        y = p/pow;
        sum = x + y;
        if (n==1)
        {
            System.out.println("It is Kaprekar Number : "+n);
        }
        else if(x==0||y==0)
        {
            System.out.println("It is not Kaprekar Number : "+n);
        }
        else if(sum==n)
        {
            System.out.println("It is Kaprekar Number : "+n);
        }
        else
        {
            System.out.println("It is not a Kaprekar Number : "+n);
        }
    }//end of main method
}//end of class
 

For Proper Understanding Watch the Video :-



Watch this video : Kaprekar Number in JAVA

All the best :)
Keep Learning :)



Comments

Popular posts from this blog

Frequency of each digit of a number in Java

Trimorphic Number in JAVA

Tri-Automorphic Number in JAVA