Happy Number | Java program to check a number is a Happy number or not ; Utility method to return sum of square of digit of n ; method return true if n is Happy number ; initialize slow and fast by n ; move slow number by one iteration ; move fast number by two iteration ; if both number meet at 1 , then return true ; Driver code to test above methods
class GFG { static int numSquareSum ( int n ) { int squareSum = 0 ; while ( n != 0 ) { squareSum += ( n % 10 ) * ( n % 10 ) ; n /= 10 ; } return squareSum ; } static boolean isHappynumber ( int n ) { int slow , fast ; slow = fast = n ; do { slow = numSquareSum ( slow ) ; fast = numSquareSum ( numSquareSum ( fast ) ) ; } while ( slow != fast ) ; return ( slow == 1 ) ; } public static void main ( String [ ] args ) { int n = 13 ; if ( isHappynumber ( n ) ) System . out . println ( n + " ▁ is ▁ a ▁ Happy ▁ number " ) ; else System . out . println ( n + " ▁ is ▁ not ▁ a ▁ Happy ▁ number " ) ; } }