Kaprekar Number - ISC Computer Science 2010 Practical

A positive whole number 'n' that has 'd' number of digits is squared and split into two pieces, a right-hand piece that has 'd' digits and a left-hand piece that has remaining 'd' or 'd - 1' digits. If the sum of the two pieces is equal to the number, then 'n' is a Kaprekar number. The first few Kaprekar numbers are: 1, 9, 45, 297, ...

Example 1:
9
92 = 81
Right-hand piece of 81 = 1
Left-hand piece of 81 = 8
Sum = 1 + 8 = 9

Example 2:
45
452 = 2025
Right-hand piece of 2025 = 25
Left-hand piece of 2025 = 20
Sum = 25 + 20 = 45

Example 3:
297
2972 = 88209
Right-hand piece of 88209 = 209
Left-hand piece of 88209 = 88
Sum = 209 + 88 = 297

Given the two positive integers p and q, where p < q, write a program to determine how many Kaprekar numbers are there in the range between p and q (both inclusive) and output them.

The input contains two positive integers p and q. Assume p < 5000 and q < 5000. You are to output the number of Kaprekar numbers in the specified range along with their values in the format specified below:

Sample Data:
INPUT:
p = 1
q = 1000
OUTPUT:
THE KAPREKAR NUMBERS ARE:
1, 9, 45, 55, 99, 297, 703, 999
FREQUENCY OF KAPREKAR NUMBERS IS: 8

import java.util.Scanner;
class Kaprekar{
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.print("p = ");
        int p = Integer.parseInt(in.nextLine());
        System.out.print("q = ");
        int q = Integer.parseInt(in.nextLine());
        if(p >= q || p >= 5000 || q >= 5000){
            System.out.println("INVALID RANGE!");
            return;
        }
        int count = 0;
        System.out.println("THE KAPREKAR NUMBERS ARE:");
        for(int i = p; i <= q; i++){
            int left = 0;
            int right = 0;
            String l = "";
            String r = "";
            int digits = countDigits(i);
            int sq = i * i;
            for(int j = 1; j <= digits; j++){
                int d = sq % 10;
                r = d + r;;
                sq /= 10;
            }
            l = l + sq;
            left = Integer.parseInt(l);
            right = Integer.parseInt(r);
            int sum = left + right;
            if(i == sum){
                count++;
                if(count == 1)
                    System.out.print(i);
                else
                    System.out.print(", " + i);
            }
        }
        System.out.println("\nFREQUENCY of KAPREKAR NUMBERS IS: " + count);
    }
    public static int countDigits(int n){
        int count = 0;
        if(n == 0)
            return 1;
        for(int i = n; i != 0; i /= 10)
            count++;
        return count;
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory