0% found this document useful (0 votes)
6 views2 pages

Program 4

Uploaded by

Rahul Ganguly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Program 4

Uploaded by

Rahul Ganguly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Program 4:-

Question: A positive natural number with p digits is said to be Kaprekar number if the
representation of its square can be split into two parts (where the second part has p digits),
that add up to the original number.
Example: 452 = 2025 and 20 + 25 = 45. Hence 45 is a Kaprekar number
2972 = 88209 and 88 + 209 = 297 Hence 297 is a Kaprekar number
Write a program to generate and show all Kaprekar numbers less than 1000.

Algorithm:

Step 1: START
Step 2: create a mono-parameterized boolean method named isKaprekar
Sub-Steps:
2.1: Set s = “” + a2
2.2: Set n1 = last n digits, where n=no. of digits of original no. & n2 = preceding digits
2.3: If n1 + n2 = a, return true, else false
Step 3: In main, print “All kaprekar no. less than 1000”
Step 4: Start a loop for i=4to i<1000, i increased by 1 every iteration, and if condition is true
print the no.
Step 5: END

Source code:

import java.util.Scanner;

public class Prog_4 {

static boolean isKaprekar(int a){


String s = "" + (a*a);
int n1 = Integer.parseInt( s.substring(s.length() - (""+a).length() ) ); //Extracting n digits
int n2 = Integer.parseInt( s.substring( 0, s.length() - (""+a).length() ) ); //and prev digits

if( (n1 + n2)==a) //Conditions for kaprekar


return true;
else
return false;
}
public static void main(String[] args) {

System.out.println("All Kaprekar numbers less than 1000 :-");

for(int i=4;i<1000;i++)
if(isKaprekar(i)) //Checking whether kaprekar or not
System.out.println(i);

} //end of main

} //end of class

Variable Description:

Variable Name Data Type Description

s String Stores squared value as string

Stores last n digits, where


n1 int
n=no. of digits of original no.
n2 int Stores preceding digits

i int Used to operate for-loop

Sample Input / Output:

You might also like