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

Kaprekar Numbers in a Range

Download .java

Question

Accept p and q where 1 <= p < q < 5000. A positive integer n is Kaprekar if n² can be split into left and right parts, with the right part containing as many digits as n, whose sum is n. List the Kaprekar numbers in the range.

Step 1: Start. Step 2: Declare the variables and data structures required for the task. Step 3: Input p and q and validate their limits. Step 4: For each n in the range, calculate square = n*n. Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution. Step 6: Set divisor = 10 raised to the number of digits in n. Step 7: Split square into left = square/divisor and right = square%divisor. Step 8: If left + right equals n, add n to the result list. Step 9: Display the list or NIL. Step 10: Display the frequency and stop. Step 11: Stop.
Java
import java.util.*;
class KaprekarRange {
    static boolean isKaprekar(int n) {
        long square = (long) n * n;
        long divisor = 10;
        int digits = String.valueOf(n).length();
        for (int i = 1; i < digits; i++) {
            divisor *= 10;
        }
    return square / divisor + square % divisor == n;
}
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int p = sc.nextInt(), q = sc.nextInt();
    if (p < 1 || p >= q || q >= 5000) {
        System.out.println("INVALID INPUT");
        return;
    }
ArrayList<Integer> list = new ArrayList<>();
for (int n = p; n <= q; n++) {
    if (isKaprekar(n)) {
        list.add(n);
    }
}
System.out.println("THE KAPREKAR NUMBERS ARE:");
System.out.println(list.isEmpty() ? "NIL" : list.toString().replace("[", "").replace("]", ""));
System.out.println("FREQUENCY OF KAPREKAR NUMBERS IS: " + list.size());
}
}
Input: 1 100 Output: THE KAPREKAR NUMBERS ARE: 1, 9, 45, 55, 99 FREQUENCY OF KAPREKAR NUMBERS IS: 5
← Previous Program 66 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.