Keith Number | C # program to check if a number is Keith or not ; 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 " . ; int temp = x , 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 program
using System ; using System . Collections ; class GFG { static bool isKeith ( int x ) { ArrayList terms = new ArrayList ( ) ; while ( temp > 0 ) { terms . Add ( temp % 10 ) ; temp = temp / 10 ; n ++ ; } terms . Reverse ( ) ; int next_term = 0 , i = n ; while ( next_term < x ) { next_term = 0 ; for ( int j = 1 ; j <= n ; j ++ ) next_term += ( int ) terms [ i - j ] ; terms . Add ( next_term ) ; i ++ ; } return ( next_term == x ) ; } public static void Main ( ) { if ( isKeith ( 14 ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; if ( isKeith ( 12 ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; if ( isKeith ( 197 ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }