-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeith_Number.java
67 lines (63 loc) · 2.77 KB
/
Keith_Number.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
62
63
64
65
66
67
// In this section, we will learn what is Keith number and also create Java
// programs to check if the given number is Keith or not. The Keith number
// program frequently asked in Java coding test.
// Keith Number
// A positive n digit number X is called a Keith number (or repfigit number) if
// it is arranged in a special number sequence generated using its digits. The
// special sequence has first n terms as digits of x and other terms are
// recursively evaluated as the sum of previous n terms. For example, 197, 19,
// 742, 1537, etc.
import java.util.*;
class Keith_Number {
// user-defined function that checks if the given number is Keith or not
static boolean isKeith(int x) {
// List stores all the digits of the X
ArrayList<Integer> terms = new ArrayList<Integer>();
// n denotes the number of digits
int temp = x, n = 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);
int next_term = 0, i = n;
// finds next term for the series
// loop executes until the condition returns true
while (next_term < x) {
next_term = 0;
// next term is the sum of previous n terms (it depends on number of digits the
// number has)
for (int j = 1; j <= n; j++)
next_term = next_term + terms.get(i - j);
terms.add(next_term);
i++;
}
// when the control comes out of the while loop, there will be two conditions:
// either next_term will be equal to x or greater than x
// if equal, the given number is Keith, else not
return (next_term == x);
}
// driver code
public static void main(String[] args) {
// calling the user-defined method inside the if statement and print the result
// accordingly
if (isKeith(19))
System.out.println("Yes, the given number is a Keith number.");
else
System.out.println("No, the given number is not a Keith number.");
if (isKeith(742))
System.out.println("Yes, the given number is a Keith number.");
else
System.out.println("No, the given number is not a Keith number.");
if (isKeith(4578))
System.out.println("Yes, the given number is a Keith number.");
else
System.out.println("No, the given number is not a Keith number.");
}
}