KEITH NUMBER
Before moving on to code let us talk about what is Keith number . A number is said to be Keith Number, if it appears in the sequence where first n numbers are digits of number itself and rest are formed by repeatedly adding the previous n numbers of the sequence . It is illustrated in the example below:
eg.
1. 14 is a Keith number
Sequence formed by 14 is 1, 4, 5, 9, 14, . . . .
First two numbers(1, 4) are digits of number(14) itself and rest are formed by adding the previous two numbers of sequence(1+4=5, 5+4=9, 9+5=14).
2. 197 is a Keith number
Sequence formed by 197 is 1, 9, 7, 17, 33, 57, 107, 197, . . . .
First three numbers(1, 9, 7) are digits of number(197) itself and rest are formed by adding the previous two numbers of sequence(1+9+7=17, 9+7+17=33, 7+17+33=57 ,17+33+57=107 , 33+57+107-=197).
NOTE:t is recommended that you first try this question by yourself.
Python Code
# Program to check for keith number
t=int(input("Enter the number of times you want to execute the program "))
#This loop is for the number of times you want to execute the program.. You don't have to restart the program again and again
for _ in range(t):
n=input("Enter a number to be checked for a Keith number ")
length=len(n)
lst=[]
# Appending the digits of number to a list
for i in n:
lst.append(int(i))
sum=0
c=0
# We will break the loop when sum of the last n numbers of seequence will be greater than n itself
while sum<int(n):
#There is no keith number from 1 to 10
if int(n)>=0 and int(n)<=10:
break
# Adding the last n numbers from the sequence
sum=0
for i in range(len(lst),len(lst)-length,-1):
sum+=lst[i-1]
lst.append(sum)
# If sum is equal to n then break the loop and initialize c to 1
if sum==int(n):
c=1
break
if c==1:
print(f"{n} is a Keith number")
else:
print(f"{n} is a not Keith number")
Output:
Enter the number of times you want to execute the program 6
Enter a number to be checked for a Keith number 14
14 is a Keith number
Enter a number to be checked for a Keith number 12
12 is a not Keith number
Enter a number to be checked for a Keith number 5752090994058710841670361653731519
5752090994058710841670361653731519 is a Keith number
Enter a number to be checked for a Keith number 197
197 is a Keith number
Enter a number to be checked for a Keith number 47
47 is a Keith number
Enter a number to be checked for a Keith number 565
565 is a not Keith number
Please share this post if this was useful and comment below your doubts and questions
Comments
Post a Comment
Please do not enter any spam link in the comment box