A Kaprekar number is a number in which the sqaure of the number is split into two parts and the sum of those two parts is equal to number. For e.x- 452=2025 -> 20 + 45 == 45, 2972=88209 -> 88 + 209 == 297.
import java.util.Scanner;
class Kaprekar {
public static void main(String[] args) {
Kaprekar a = new Kaprekar();
a.input();
}
void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if (is_kapr(n))
System.out.println("Is a Kaprekar number");
else
System.out.println("Is not a Kaprekar number");
sc.close();
}
boolean is_kapr(int n) {
String nm = String.valueOf(n * n); // number converted to a string
int ln = nm.length(), first = 0, second = 0;
first = Integer.parseInt(nm.substring(0, ln / 2));
second = Integer.parseInt(nm.substring(ln / 2));
return first + second == n;
}
}
Name | Type | Uses |
---|---|---|
void main() | ||
a | Kaprekar | Object to call the methods |
boolean iskaprekar() | ||
n | int | argument :- variable to test for kaprekar number |
nm | String | to store string value of sqaure of 'n' |
ln | int | to store length of string |
first | int | to store first part of the substring |
second | int | to store second part of the substring |
void input() | ||
sc | Scanner | To Take User Input |
n | int | to store entered number |