Capricorn or Kaprekar Number Program in Java

Capricorn or Kaprekar Number Program in Java
Capricorn or Kaprekar Number Program in Java

A number is called Capricorn or Kaprekar number whose square is divided into two parts in any conditions and parts are added, the additions of parts is equal to the number, is called Capricorn or Kaprekar number.


import java.util.Scanner;

public class CapricornNumber
{

    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number=");
        int n = scanner.nextInt();
         boolean isCapricorn = false;
         
        int square = n * n;
        int temp = square;
        int contDigits = 0;
        
        while (temp > 0)
        {
            contDigits++;
            temp /= 10;
        }
       
        for (int i = 1; i < contDigits; i++)
        {
            int divisor = (int) Math.pow(10, i);
            int quotient = square / divisor;
            int remainder = square % divisor;
            if (quotient + remainder == n)
            {
                isCapricorn = true;
            }
        }
        if (isCapricorn)
        {
            System.out.println("Capricorn/Kaprekar number");
        } else
        {
            System.out.println("Not Capricorn/Kaprekar number");
        }
    }
}

Output:

Enter a number=297
Capricorn/Kaprekar number
java java programs number based program

Frequently Asked Questions

A number is called Capricorn or Kaprekar number whose square is divided into two parts in any conditions and parts are added, the additions of parts is equal to the number, is called Capricorn or Kaprekar number.