text: Count of numbers in range [ L , R ] having sum of digits of its square equal to square of sum of digits | C # 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
code: using System ; using System . Collections . Generic ; class GFG { static bool 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 ; char [ ] charArray = s . ToCharArray ( ) ; Array . Reverse ( charArray ) ; s = new string ( charArray ) ; int cur = 1 ; for ( int i = 0 ; i < s . Length ; i ++ ) { val += ( ( int ) s [ i ] - ( int ) '0' ) * cur ; cur *= 10 ; } return val ; } static void generate ( string s , int len , HashSet < int > uniq ) { if ( s . Length == len ) { if ( check ( convert ( s ) ) ) { uniq . Add ( convert ( s ) ) ; } return ; } for ( int i = 0 ; i <= 3 ; i ++ ) { generate ( s + Convert . ToChar ( i + ( int ) '0' ) , len , uniq ) ; } } static int totalNumbers ( int L , int R ) { int ans = 0 ; int max_len = ( int ) Math . Log10 ( R ) + 1 ; HashSet < int > uniq = new HashSet < int > ( ) ; for ( int i = 1 ; i <= max_len ; i ++ ) { generate ( " " , i , uniq ) ; } foreach ( int x in uniq ) { if ( x >= L && x <= R ) { ans ++ ; } } return ans ; } public static void Main ( ) { int L = 22 , R = 22 ; Console . Write ( totalNumbers ( L , R ) ) ; } }