Google News
logo
Java program to Keith Number
A Keith number is an n-digit number that appears in a special sequence defined by the digits in the number itself.

The sequence is obtained by summing up the digits in the number, and then adding the sum to the end of the sequence. The process is repeated until the sequence contains the original number.

For example, the number 197 is a Keith number because it appears in the following sequence : 1, 9, 7, 17, 33, 57, 107, 197.

Here's a Java program that checks whether a given number is a Keith number or not :
Program :
import java.util.*;

public class KeithNumber {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();

        List<Integer> digits = new ArrayList<>();
        int temp = n;
        while (temp != 0) {
            digits.add(temp % 10);
            temp /= 10;
        }
        Collections.reverse(digits);

        List<Integer> sequence = new ArrayList<>();
        sequence.addAll(digits);

        while (sequence.get(sequence.size() - 1) < n) {
            int sum = 0;
            for (int i = sequence.size() - digits.size(); i < sequence.size(); i++) {
                sum += sequence.get(i);
            }
            sequence.add(sum);
        }

        if (sequence.get(sequence.size() - 1) == n) {
            System.out.println(n + " is a Keith number.");
        } else {
            System.out.println(n + " is not a Keith number.");
        }
    }
}
Output :
Enter a number: 197
197 is a Keith number.
Enter a number: 199
199 is not a Keith number.

*
The program first reads in a number from the user. It then extracts the digits of the number and stores them in a list.

* The program then creates a sequence by adding the digits together and appending the sum to the end of the sequence.

* The loop continues until the sequence contains the original number.

* Finally, the program checks whether the last number in the sequence is equal to the original number, and prints the appropriate message.