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: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int num ) { int sm = 0 ; int num2 = num * num ; while ( num ) { sm += num % 10 ; num /= 10 ; } int sm2 = 0 ; while ( num2 ) { sm2 += num2 % 10 ; num2 /= 10 ; } return ( ( sm * sm ) == sm2 ) ; } int convert ( string s ) { int val = 0 ; reverse ( s . begin ( ) , s . end ( ) ) ; int cur = 1 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { val += ( s [ i ] - '0' ) * cur ; cur *= 10 ; } return val ; } void generate ( string s , int len , set < int > & uniq ) { if ( s . size ( ) == len ) { if ( check ( convert ( s ) ) ) { uniq . insert ( convert ( s ) ) ; } return ; } for ( int i = 0 ; i <= 3 ; i ++ ) { generate ( s + char ( i + '0' ) , len , uniq ) ; } } int totalNumbers ( int L , int R ) { int ans = 0 ; int max_len = log10 ( R ) + 1 ; set < int > uniq ; for ( int i = 1 ; i <= max_len ; i ++ ) { generate ( " " , i , uniq ) ; } for ( auto x : uniq ) { if ( x >= L && x <= R ) { ans ++ ; } } return ans ; } int main ( ) { int L = 22 , R = 22 ; cout << totalNumbers ( L , R ) ; }