Java Program To Find All Kaprekar Number In A Given Range

You are currently viewing Java Program To Find All Kaprekar Number In A Given Range

Java Program To Find All Kaprekar Number In A Given Range

import java.util.Scanner;

public class KaprekarNumberInRange {

  public static boolean isKaprekar(int number) {

     // declare variables
     int square = 0;
     int temp = 0;
     int countDigits = 0;
     int firstPart = 0;
     int secondPart = 0;
     int sum = 0;

     // calculate square value of the number
     square = number * number;

     // count number of digits in the square
     temp =square;
     while(temp!=0) {
        countDigits++;
        temp /= 10; 
     }

     // divide square into two parts and 
     // check it's sum is equal to the number?
     for(int i=countDigits-1; i>0; i--) {

        // find first part
        firstPart = square / (int)Math.pow(10, i);
        // find second part
        secondPart = square % (int)Math.pow(10, i);

        // check have any part only 0
        if(firstPart == 0 || secondPart == 0)
        continue;

        // find sum value
        sum = firstPart + secondPart;

        // compare sum and number
        if( sum == number )
        return true;
     }
     return false;
  }

  public static void main(String[] args) {

     // declare variables
     int minRange = 0, maxRange = 0;

     // create Scanner class object
     Scanner scan = new Scanner(System.in);
     // read inputs
     System.out.print("Enter min value of range:: ");
     minRange = scan.nextInt();
  
     System.out.print("Enter max value of range:: ");
     maxRange = scan.nextInt();

     // check number 
     System.out.println("The kaprekar numbers from "+
          minRange+" to "+ maxRange+" are:: ");

     for(int i=minRange; i<=maxRange; i++) {
        if(isKaprekar(i))
	   System.out.print(i+" ");
     }

     // close Scanner class object
     scan.close();
  }
}

Output

Enter min value of range:: 1
Enter max value of range:: 100
The kaprekar numbers from 1 to 100 are::
9 45 55 99

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply