-
Notifications
You must be signed in to change notification settings - Fork 61
/
KaprekarNumber.java
61 lines (56 loc) · 1.54 KB
/
KaprekarNumber.java
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.java.numbers;
import java.util.Scanner;
/*
* Kaprekar Number
*
* A Kaprekar number is a number whose square
* when divided into two parts and such that
* sum of parts is equal to the original number
* and none of the parts has value 0.
*
* for example n = 45
* square of 45 is = 2025
* 2025 = 20 + 25 = 45
*
* n Square 2 parts sum
* 9 81 8 + 1
* 45 2025 20 + 25
* 55 3025 30 + 25
* 99 9801 98 + 01
* 297 88209 88 + 209
* 703 494209 494 + 209
* 999 998001 998 + 001
*
*/
public class KaprekarNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any positive number :: ");
int num = Integer.parseInt(scanner.nextLine().trim());
if(isKaprekarNumber(num) == true )
System.out.println("Given number "+num+" is a Kaprekar Number.");
else
System.out.println("Given number "+num+" is NOT a Kaprekar Number.");
scanner.close();
}
public static boolean isKaprekarNumber(int num){
long square = num * num;
String str = Long.toString(square);
for(int i=1;i<str.length();i++){
String part1 = str.substring(0,i);
String part2 = str.substring(i,str.length());
long l1 = Long.valueOf(part1);
long l2 = Long.valueOf(part2);
if(l1 > 0 && l2 > 0 && l1+l2 == num)
return true;
}
return false;
}
}
/*
OUTPUT
Enter any positive number :: 45
Given number 45 is a Kaprekar Number.
Enter any positive number :: 20
Given number 20 is NOT a Kaprekar Number.
*/