Count of numbers in range [ L , R ] having sum of digits of its square equal to square of sum of digits | 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
function check ( num ) { let sm = 0 ; let num2 = num * num ; while ( num ) { sm += num % 10 ; num = Math . floor ( num / 10 ) ; } let sm2 = 0 ; while ( num2 ) { sm2 += num2 % 10 ; num2 = Math . floor ( num2 / 10 ) ; } return sm * sm == sm2 ; } function convert ( s ) { let val = 0 ; s = s . split ( " " ) . reverse ( ) . join ( " " ) ; let cur = 1 ; for ( let i = 0 ; i < s . length ; i ++ ) { val += ( s [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ) * cur ; cur *= 10 ; } return val ; } function generate ( s , len , uniq ) { if ( s . length == len ) { if ( check ( convert ( s ) ) ) { uniq . add ( convert ( s ) ) ; } return ; } for ( let i = 0 ; i <= 3 ; i ++ ) { generate ( s + String . fromCharCode ( i + " " . charCodeAt ( 0 ) ) , len , uniq ) ; } } function totalNumbers ( L , R ) { let ans = 0 ; let max_len = Math . log10 ( R ) + 1 ; let uniq = new Set ( ) ; for ( let i = 1 ; i <= max_len ; i ++ ) { generate ( " " , i , uniq ) ; } for ( let x of uniq ) { if ( x >= L && x <= R ) { ans ++ ; } } return ans ; } let L = 22 , R = 22 ; document . write ( totalNumbers ( L , R ) ) ;