Keith Number in Java

An n-digit number N is a Keith Number if it forms a Fibonacci-like sequence that begins with the digits of the number itself. The most significant digit is followed by the rest of the digits. Now each subsequent term is the sum of the previous n terms, and the number N itself appears in this sequence.

Consider the number 197.
1 + 9 + 7 = 17
9 + 7 + 17 = 33
7 + 17 + 33 = 57
17 + 33 + 57 = 107
33 + 57 + 107 = 197 (the number itself)

14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, … are some of the Keith Numbers.

import java.io.*;
class Keith{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("N = ");
        long n = Long.parseLong(br.readLine());
        int count = countDigits(n);
        long terms[] = new long[count];
        int index = count - 1;
        long next = 0;
        for(long i = n; i != 0; i /= 10){
            terms[index--] = i % 10;
            next += i % 10;
        }
        while(next < n){
            for(int i = 1; i < count; i++){
                terms[i - 1] = terms[i];
            }
            terms[count - 1] = next;
            next = 0;
            for(int i = 0; i < count; i++)
                next += terms[i];
        }
        if(next == n)
            System.out.println(n + " is a Keith Number.");
        else
            System.out.println(n + " is not a Keith Number.");
    }
    public static int countDigits(long n){
        int count = 0;
        while(n != 0){
            count++;
            n /= 10;
        }
        return count; 
    }
}

Leave a Reply