Kaprekar Number
In mathematics, a non-negative integer is called a “Kaprekar number” if its square can be split into two parts that add up to the original number. For instance, 45 is a Kaprekar number, because 452 = 2025 and 20 + 25 = 45. Kaprekar numbers are named after D. R. Kaprekar.
Ex:
9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
import java.util.*;
public class Kaprekar
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int n, c=0, n2, sq, pow;
System.out.print("Enter the number: ");
n = sc.nextInt(); //Taking input
n2 = n; //Initialising copy
sq = n*n; //Storing square
while(n>0)
{
n = n/10; //Counting the number of digits
c++;
}
pow = (int)Math.pow(10, c); //Type casting
/*sq%pow gives the last c digits from the end of a square
where as sq/pow returns the starting digits*/
if(sq%pow + sq/pow == n2)
System.out.println("The number is a Kaprekar number");
else
System.out.println("The number is not a Kaprekar number");
}
}
/*Type casting is the process of converting a value of a higher datatype to a value of lower data type.
This results in a loss of data therefore is not automatically allowed by Java.
ex:
double x = 2.3;
int y = x; -->This will give a compile time error as double is a higher order data type as compared to int
therefore:
int y = (int)x;
Order of data types:
byte
short
char
int
long
float
double
String
*/
|
Output