- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathKeithNumber.java
60 lines (56 loc) · 1.95 KB
/
KeithNumber.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
packagecom.thealgorithms.maths;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.Scanner;
finalclassKeithNumber {
privateKeithNumber() {
}
// user-defined function that checks if the given number is Keith or not
staticbooleanisKeith(intx) {
// List stores all the digits of the X
ArrayList<Integer> terms = newArrayList<>();
// n denotes the number of digits
inttemp = x;
intn = 0;
// executes until the condition becomes false
while (temp > 0) {
// determines the last digit of the number and add it to the List
terms.add(temp % 10);
// removes the last digit
temp = temp / 10;
// increments the number of digits (n) by 1
n++;
}
// reverse the List
Collections.reverse(terms);
intnextTerm = 0;
inti = n;
// finds next term for the series
// loop executes until the condition returns true
while (nextTerm < x) {
nextTerm = 0;
// next term is the sum of previous n terms (it depends on number of digits the number
// has)
for (intj = 1; j <= n; j++) {
nextTerm = nextTerm + terms.get(i - j);
}
terms.add(nextTerm);
i++;
}
// when the control comes out of the while loop, there will be two conditions:
// either nextTerm will be equal to x or greater than x
// if equal, the given number is Keith, else not
return (nextTerm == x);
}
// driver code
publicstaticvoidmain(String[] args) {
Scannerin = newScanner(System.in);
intn = in.nextInt();
if (isKeith(n)) {
System.out.println("Yes, the given number is a Keith number.");
} else {
System.out.println("No, the given number is not a Keith number.");
}
in.close();
}
}