Keith Number | Returns true if x is Keith , else false . ; Store all digits of x in a vector " terms " Also find number of digits and store in " n " . ; n = 0 ; n is number of digits in x ; To get digits in right order ( from MSB to LSB ) ; Keep finding next trms of a sequence generated using digits of x until we either reach x or a number greate than x ; Next term is sum of previous n terms ; When the control comes out of the while loop , either the next_term is equal to the number or greater than it . If next_term is equal to x , then x is a Keith number , else not ; Driver Code
def isKeith ( x ) : NEW_LINE INDENT terms = [ ] ; NEW_LINE temp = x ; NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT terms . append ( temp % 10 ) ; NEW_LINE temp = int ( temp / 10 ) ; NEW_LINE n += 1 ; NEW_LINE DEDENT terms . reverse ( ) ; NEW_LINE next_term = 0 ; NEW_LINE i = n ; NEW_LINE while ( next_term < x ) : NEW_LINE INDENT next_term = 0 ; NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT next_term += terms [ i - j ] ; NEW_LINE DEDENT terms . append ( next_term ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT return ( next_term == x ) ; NEW_LINE DEDENT print ( " Yes " ) if ( isKeith ( 14 ) ) else print ( " No " ) ; NEW_LINE print ( " Yes " ) if ( isKeith ( 12 ) ) else print ( " No " ) ; NEW_LINE print ( " Yes " ) if ( isKeith ( 197 ) ) else print ( " No " ) ; NEW_LINE