← All resources

Kaprekar Number – ISC Practical 2010 – Question 2

A positive whole number ‘n’ that has ‘d’ number of digits is square 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 number are 9, 45, 297………….

For example 297 is a Kaprekar number because:

2972 = 88209, right – hand piece of 88209 = 209 and left I hand piece of 88209 = 88

Sum = 209 = 8 =297, is equal to the number.

Given the two positive integers p and q, where p<q,, write a program to determine how many Kaprekar number 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 number in the specified range along with their values the format specified below.

SAMPLE DATA:

INPUT:

P = 1

Q = 1000

OUTPUT:

THE KAPREKAR NUMBER ARE :-

1, 9,45, 55, 9,297,703, 999

FREQUENCY OF KAPREKAR NUMBER IS : 8

Enter the two limits(Both &lt;5000):
1
1000
The Kaprekar Numbers are:
1
9
45
55
99
297
703
999
Frequency: 8
import java.io.*;
public class Kaprekar
{
    public boolean isKaprekar(int n)
    {
        int n2, l, p1, p2;
        n2 = n*n;
        l = (""+n).length();
        p1 = n2%(int)Math.pow(10,l);
        p2 = n2/(int)Math.pow(10,l);
        if((p1+p2)==n)
        return true;
        return false;
    }
    public static void main()throws IOException
    {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        int p, q, i, c=0;
        Kaprekar ob = new Kaprekar();
        System.out.println("Enter the two limits(Both &lt;5000):");
        p = Integer.parseInt(r.readLine());
        q = Integer.parseInt(r.readLine());
        if(p &lt; 0 || q &lt; 0 || p &gt;= 5000 || q &gt;= 5000 || p &gt;= q)
        System.out.println("The values are not in limit or improper.");
        else
        {
            System.out.println("The Kaprekar Numbers are:");
            for(i=p;i &lt;= q;i++)
            {
                if(ob.isKaprekar(i))
                {
                    System.out.println(i);
                    c++;
                }
            }
            System.out.println("Frequency: "+c);
        }
    }
}