Blog

Keith Numbers in Java

What is a Keith Number?
“A Keith number is an n-digit integer N>9 such that if a Fibonacci-like sequence (in which each term in the sequence is the sum of the n previous terms) is formed with the first n terms taken as 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, 1+9+7=179+7+17=337+17+33=5717+33+57=10733+57+107=197, … (Keith). Keith numbers are also called repfigit (repetitive fibonacci-like digit) numbers.”
Definition from http://mathworld.wolfram.com/KeithNumber.html

Here is another example:
47
add 4 to 7, then write 7
11,7
11+7 gives 18
11,18
11+18=29
18,29
18+29 is 47.
Hence it is a Keith Number.

If the generated sum goes beyond the original number it is not Keith.
Trying with 45 for instance

9,5,
9,14,
14,23,
23,37,
37,60,
Not Keith

public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println(“Enter a number to check”);
int number=s.nextInt();
String num=””+number;
int[] ar=new int[num.length()];
for(int i=0;i<=num.length()-1;i++)
{
for(int j=i;j<num.length();j++)
{
ar[i]+=Integer.parseInt(“”+num.charAt(j));
}
}
for(int k=0;k<ar.length;k++)
{
System.out.print(ar[k]+”,”);
}
System.out.println();
for(int i=0;i<=ar.length-1;i++)
{
int sum=0;
for(int j=0;j<=i;j++)
{
sum=sum + ar[j];
}
ar[i]=sum;
}
for(int k=0;k<ar.length;k++)
{
System.out.print(ar[k]+”,”);
}
System.out.println();
while(true)
{
int sum=0;
for(int i=0;i<=ar.length-1;i++)
sum=sum + ar[i];
for(int i=0;i<=ar.length-2;i++)
ar[i]=ar[i+1];
ar[ar.length-1]=sum;
for(int k=0;k<ar.length;k++)
{
System.out.print(ar[k]+”,”);
}
System.out.println();
if(sum==number)
{
System.out.println(“Keith”);
return;
}
if(sum>number)
{
System.out.println(“Not Keith”);
return;
}
}
}

Output

Enter a number to check
742
13,6,2,
13,19,34,
19,34,66,
34,66,119,
66,119,219,
119,219,404,
219,404,742,
Keith

Cover image credit and more information on this youtube video.
https://www.youtube.com/watch?v=C7c6QvCqgC4