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 " . ; let 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
function isKeith ( x ) { let terms = [ ] ; let temp = x ; while ( temp > 0 ) { terms . push ( temp % 10 ) ; temp = parseInt ( temp / 10 ) ; n ++ ; } terms = terms . reverse ( ) ; let next_term = 0 ; let i = n ; while ( next_term < x ) { next_term = 0 ; for ( let j = 1 ; j <= n ; j ++ ) next_term += terms [ i - j ] ; terms . push ( next_term ) ; i ++ ; } return ( next_term == x ) ; } isKeith ( 14 ) ? document . write ( " " ) : document . write ( " " ) ; isKeith ( 12 ) ? document . write ( " " ) : document . write ( " " ) ; isKeith ( 197 ) ? document . write ( " " ) : document . write ( " " ) ;