Keith Number | Java 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
import java . io . * ; import java . util . * ; class GFG { static boolean isKeith ( int x ) { ArrayList < Integer > terms = new ArrayList < Integer > ( ) ; while ( temp > 0 ) { terms . add ( temp % 10 ) ; temp = temp / 10 ; n ++ ; } Collections . reverse ( terms ) ; int next_term = 0 , i = n ; while ( next_term < x ) { next_term = 0 ; for ( int j = 1 ; j <= n ; j ++ ) next_term += terms . get ( i - j ) ; terms . add ( next_term ) ; i ++ ; } return ( next_term == x ) ; } public static void main ( String [ ] args ) { if ( isKeith ( 14 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; if ( isKeith ( 12 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; if ( isKeith ( 197 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }