Pankaj Gupta Scholar
Program to Check for Keith Number
A Keith number is an n-digit number that appears as a term in a sequence, where the first n terms are its own digits, and each following term is the sum of the previous n terms. For example, 197 is a Keith number because starting with 1, 9, 7, and continually adding the last three terms together, 197 appears in the sequence: 1, 9, 7, 17, 33, 57, 107, 197
Program:
import java.io.*;
class Keith {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(“Enter the number : “); // inputting the number
int n = Integer.parseInt(br.readLine());
int c = n;
String s = Integer.toString(n);
int d = s.length(); // finding the number of digits (d) in the number
int arr[] = new int[d]; // array for storing the terms of the series
for(int i = d – 1; i >= 0; i–) {
arr[i] = c % 10; // storing the digits of the number in the array
c = c / 10;
}
int sum = 0;
while(sum < n) {
sum = 0;
for(int j = 0; j < d; j++) {
sum = sum + arr[j];
}
for(int j = 0; j < d – 1; j++) {
arr[j] = arr[j + 1];
}
arr[d – 1] = sum;
}
if(sum == n)
System.out.println(“The number is a Keith Number”);
else
System.out.println(“The number is not a Keith Number”);
}
}
How this program works
Program Breakdown
The program imports necessary classes for input handling.
It reads an integer
nfrom the user.It determines the number of digits
dinn(using string conversion and length).It creates an array
arrto store the digits of the number in order.It fills this array with the individual digits of
n.
Sequence Generation
The heart of the logic is the while loop, which keeps generating new terms in the sequence by summing the elements of the array.
Each time, after summing, the digits in the array are shifted left (removing the oldest digit), and the new sum is appended to the end.
This loop continues until the sum reaches or exceeds
n.
Final Check
If the sequence hits exactly
n, then it is a Keith number, so “The number is a Keith Number” is printed.If not, it’s not a Keith number.
Key Points in the Example Code
Let’s say the input is
197: it will fill the array as , then produce 17, 33, 57, 107, and finally 197.If the number appears in its sequence, it’s a Keith number.
Typical Output
If the input is 197, output is:
The number is a Keith Number.If the input is 12, output is:
The number is not a Keith Number.
This process helps determine if a number belongs to this interesting mathematical set.


