Skip to content

Commit 40e055b

Browse files
sachin4429siriak
andauthored
Added Keith No. Program (Hacktoberfest2021) (TheAlgorithms#2342)
Co-authored-by: Andrii Siriak <[email protected]>
1 parent b8ebf2d commit 40e055b

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Maths/KeithNumber.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.util.*;
2+
class KeithNumber
3+
{
4+
//user-defined function that checks if the given number is Keith or not
5+
static boolean isKeith(int x)
6+
{
7+
//List stores all the digits of the X
8+
ArrayList<Integer> terms=new ArrayList<Integer>();
9+
//n denotes the number of digits
10+
int temp = x, n = 0;
11+
//executes until the condition becomes false
12+
while (temp > 0)
13+
{
14+
//determines the last digit of the number and add it to the List
15+
terms.add(temp%10);
16+
//removes the last digit
17+
temp = temp/10;
18+
//increments the number of digits (n) by 1
19+
n++;
20+
}
21+
//reverse the List
22+
Collections.reverse(terms);
23+
int next_term = 0, i = n;
24+
//finds next term for the series
25+
//loop executes until the condition returns true
26+
while (next_term < x)
27+
{
28+
next_term = 0;
29+
//next term is the sum of previous n terms (it depends on number of digits the number has)
30+
for (int j=1; j<=n; j++)
31+
next_term = next_term + terms.get(i-j);
32+
terms.add(next_term);
33+
i++;
34+
}
35+
//when the control comes out of the while loop, there will be two conditions:
36+
//either next_term will be equal to x or greater than x
37+
//if equal, the given number is Keith, else not
38+
return (next_term == x);
39+
}
40+
//driver code
41+
public static void main(String[] args)
42+
{
43+
Scanner in = new Scanner(System.in);
44+
int n = in.nextInt();
45+
if (isKeith(n))
46+
System.out.println("Yes, the given number is a Keith number.");
47+
else
48+
System.out.println("No, the given number is not a Keith number.");
49+
}
50+
}

0 commit comments

Comments
 (0)