Program opened below. You can scroll through the algorithm, Java code and output.

Keith Number

Download .java

Question

Determine whether a positive integer appears in the sequence beginning with its digits, where each next term is the sum of the preceding d terms.

Step 1: Start and accept integer n. Step 2: Reject numbers below ten for this exercise. Step 3: Count the decimal digits of n. Step 4: Create an array containing exactly that many terms. Step 5: Extract the digits from right to left. Step 6: Store them in the array in their original left-to-right order. Step 7: Initialize the next sequence term. Step 8: Sum all terms currently present in the array. Step 9: Shift each term one place to the left. Step 10: Insert the calculated sum at the last array position. Step 11: Compare the new term with the original number. Step 12: If smaller, repeat the sum-and-shift process. Step 13: If equal, classify the number as Keith. Step 14: If greater, classify the number as not Keith. Step 15: Display the result and stop.
Java
import java.util.*;
class Keith {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        if (n < 10) {
            System.out.println("Not Keith");
            return;
        }
        int temp = n;
        int digits = 0;
        while (temp > 0) {
            digits++;
            temp /= 10;
        }
        int[] terms = new int[digits];
        temp = n;
        for (int i = digits - 1; i >= 0; i--) {
            terms[i] = temp % 10;
            temp /= 10;
        }
        int next = 0;
        do {
            next = 0;
            for (int x : terms) {
                next += x;
            }
            for (int i = 0; i < digits - 1; i++) {
                terms[i] = terms[i + 1];
            }
            terms[digits - 1] = next;
        } while (next < n);
        System.out.println(next == n ? "Keith" : "Not Keith");
    }
}
Input: 197 Output: Keith
← Previous Program 12 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.