Program opened below. You can scroll through the algorithm, Java code and output.

Kaprekar Numbers in a Range

Download .java

Question

Input positive integers p and q (p ≤ q). Display every Kaprekar number in the inclusive range and its frequency. Split the square into equal halves, or give the right half one extra digit.

Step 1: Start the program and create a Scanner object. Step 2: Read the lower limit p. Step 3: Read the upper limit q. Step 4: Reject nonpositive or reversed limits and numbers beyond the safe int-squaring range. Step 5: Set the frequency count to zero. Step 6: Visit each number n from p through q. Step 7: Calculate the square of n. Step 8: Count the square’s digits by repeated division by ten. Step 9: Calculate the right-part length, giving it the extra digit when needed. Step 10: Build a power-of-ten divisor for that many digits. Step 11: Find the left part using integer division. Step 12: Find the right part using the remainder operator. Step 13: Compare the sum of the parts with n. Step 14: Display each matching number and increase the frequency. Step 15: Print the final frequency and stop.
Java
import java.util.*;
class KaprekarRange {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int p = sc.nextInt();
        int q = sc.nextInt();
        int count = 0;
        if (p < 1 || q < p || q > 46340) {
            System.out.println("Invalid range");
            return;
        }
        for (int n = p; n <= q; n++) {
            int square = n * n;
            int temp = square;
            int digits = 0;
            do {
                digits++;
                temp /= 10;
            } while (temp > 0);
            int divisor = 1;
            for (int i = 0; i < (digits + 1) / 2; i++) {
                divisor *= 10;
            }
            // Check the two parts of the square.
            if (square / divisor + square % divisor == n) {
                System.out.println(n);
                count++;
            }
        }
        System.out.println("Frequency = " + count);
    }
}
Input: 1 1000 Output: 1, 9, 45, 55, 99, 297, 999 Frequency = 7
Program 1 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.