Programming Examples

Java program for Keith Number


Write a Program in Java to input a number and check whether it is a Keith Number or not.

Note: A Keith Number is an integer N with ‘d’ digits with the following property:

If a Fibonacci-like sequence (in which each term in the sequence is the sum of the ‘d’ previous terms) is formed, with the first ‘d’ terms being the decimal digits of the number N, then N itself occurs as a term in the sequence.

For example, 197 is a Keith number since it generates the sequence 1, 9, 7, 17, 33, 57, 107, 197, ………..

Some keith numbers are: 14 ,19, 28 , 47 , 61, 75, 197, 742, 1104, 1537……………

Sample

Enter the number : 197

The number is a Keith Number

Enter the number : 14

The number is a Keith Number

Enter the number : 53

The number is a not a Keith Number

Solution

import java.util.Scanner;
public class KeithNumber  
{
   public static void main(String[] args) 
   { 

     Scanner sc = new Scanner( System.in ); 
     System.out.print("Input a number: "); 
     int n = sc.nextInt(); 
     int n1 = n;
     String s = Integer.toString(n);
     int d=s.length();
     int arr[]=new int[n];
     int i, sum; 
     for(i=d-1; i>=0; i--)
     {
         arr[i]=n1 % 10;
         n1=n1/10;
          
     }      
     i=d; sum=0;
     while(sum<n)
     {
         sum = 0;
         for(int j=1; j<=d; j++)
         {
             sum=sum+arr[i-j];
         }
         arr[i]=sum;
         i++;
     } 
     if(sum==n)
        System.out.println("Keith Number");
     else
        System.out.println("Not a Keith Number");
    }
}
Output

Input a number: 197

Keith Number

--------------------------------------

Input a number: 14

Keith Number

----------------------------------------

Input a number: 53

Not a Keith Number

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad