Thursday 19 January 2017

Kaprekar Number...

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

For example 297 is a kaprekar number because:
2972 =88209, right hand piece of 88209=209 and left hand piece of 88209=88
Sum=209+88=297 , i.e. equal to the number.

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, 999

FREQUENCY OF KAPREKAR NUMBERS IS:8


Solution:-

import java.util.*;
public class Kaprekar
{
    public static void main(String args[])
     {
     Scanner sc=new Scanner(System.in);
         System.out.print("Enter the lower limit:");
         int p=sc.nextInt();
         System.out.print("Enter the upper limit:");
         int q=sc.nextInt();
         if(q<p)
           System.out.println("INVALID INPUT");
           else
            {
                int count=0;
                System.out.println("THE KAPREKAR NUMBERS ARE:-");
                for(int i=p;i<=q;i++) //checking between the limits
                  {
                      String s=""+i;
                      int d=s.length();
                      int sq=i*i;
                      int rd=(int)(sq%(Math.pow(10,d))); //finding right-hand piece
                      int ld=(int)(sq/(Math.pow(10,d))); //finding left-hand piece
                      if(i==(rd+ld))
                       {
                           if(count==0)
                             System.out.print(i);
                             else
                              System.out.print(","+i);
                               count++;
                       }
                    }
                    System.out.println();
                     System.out.println("FREQUENCY OF KAPREKAR NUMBERS IS:"+count);
            }
    }
}

No comments:

Post a Comment

Goldbach Number ISC 2018

Question: A Goldbach number is a positive even integer that can be expressed as the sum of two odd primes. Note: All even integer numbers ...