Count of numbers in range [ L , R ] having sum of digits of its square equal to square of sum of digits | Java program for the above approach ; Function to check if the number is valid ; Sum of digits of num ; Squared number ; Sum of digits of ( num * num ) ; Function to convert a String to an integer ; Function to generate all possible Strings of length len ; Desired String ; Take only valid numbers ; Recurse for all possible digits ; Function to calculate unique numbers in range [ L , R ] ; Initialize a variable to store the answer ; Calculate the maximum possible length ; Set to store distinct valid numbers ; Generate all possible Strings of length i ; Iterate the set to get the count of valid numbers in the range [ L , R ] ; Driver Code
import java . util . * ; class GFG { static boolean check ( int num ) { int sm = 0 ; int num2 = num * num ; while ( num > 0 ) { sm += num % 10 ; num /= 10 ; } int sm2 = 0 ; while ( num2 > 0 ) { sm2 += num2 % 10 ; num2 /= 10 ; } return ( ( sm * sm ) == sm2 ) ; } static int convert ( String s ) { int val = 0 ; s = reverse ( s ) ; int cur = 1 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { val += ( s . charAt ( i ) - '0' ) * cur ; cur *= 10 ; } return val ; } static void generate ( String s , int len , HashSet < Integer > uniq ) { if ( s . length ( ) == len ) { if ( check ( convert ( s ) ) ) { uniq . add ( convert ( s ) ) ; } return ; } for ( int i = 0 ; i <= 3 ; i ++ ) { generate ( s + ( char ) ( i + '0' ) , len , uniq ) ; } } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } static int totalNumbers ( int L , int R ) { int ans = 0 ; int max_len = ( int ) ( Math . log10 ( R ) + 1 ) ; HashSet < Integer > uniq = new HashSet < Integer > ( ) ; for ( int i = 1 ; i <= max_len ; i ++ ) { generate ( " " , i , uniq ) ; } for ( int x : uniq ) { if ( x >= L && x <= R ) { ans ++ ; } } return ans ; } public static void main ( String [ ] args ) { int L = 22 , R = 22 ; System . out . print ( totalNumbers ( L , R ) ) ; } }