Problem: Keith Number

A n digit number x is called Keith number if it appears in a special sequence (defined below) generated using its digits. The special sequence has first n terms as digits of x and other terms are recursively evaluated as sum of previous n terms.The task is to find if a given number is Keith Number or not.

Examples

```Input : x = 197
Output : 1
197 has 3 digits, so n = 3
The number is Keith because it appears in the special
sequence that has first three terms as 1, 9, 7 and
remaining terms evaluated using sum of previous 3 terms.
1, 9, 7, 17, 33, 57, 107, 197, .....

Input : x = 12
Output : 0
The number is not Keith because it doesn't appear in
the special sequence generated using its digits.
1, 2, 3, 5, 8, 13, 21, .....

Input : x = 14
Output : 1
14 is a Keith number since it appears in the sequence,
1, 4, 5, 9, 14, ...

```

Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each line contains an integer x.

Output:
For each test case in a new line print 1 if the no is a Keith number else print 0.

Constraints:
1<=T<=10000
1<=x<=10000

Example:
Input:

2
14
10
Output:
1
0

Solution:

```"""
author: loctv
language: python2.7
time: 9:05PM December 29, 2016
"""

def is_keith_number(n):
series = map(int, list(str(n)))
# start is the index at the beginning,
# after each time we sum n previous terms, each increases by 1
length, start = len(series), 0

# we only need to get atmost-n-times sum up n previous terms
while start < n:
s = sum(series[start:start+length]) # sum up n previous terms
if s > n: # there is no number in the series match n
return False
elif s == n: # n is keith number
return True
# we only add but not delete the first term
# since delete's time complexity is O(n)
series.append(s)
start += 1

if __name__ == '__main__':
t = input()
for _ in range(t):
n = input()
print 1 if is_keith_number(n) else 0

```