Count of numbers in range [ L , R ] having sum of digits of its square equal to square of sum of digits | python 3 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
from math import log10 NEW_LINE def check ( num ) : NEW_LINE INDENT sm = 0 NEW_LINE num2 = num * num NEW_LINE while ( num ) : NEW_LINE INDENT sm += num % 10 NEW_LINE num //= 10 NEW_LINE DEDENT sm2 = 0 NEW_LINE while ( num2 ) : NEW_LINE INDENT sm2 += num2 % 10 NEW_LINE num2 //= 10 NEW_LINE DEDENT return ( ( sm * sm ) == sm2 ) NEW_LINE DEDENT def convert ( s ) : NEW_LINE INDENT val = 0 NEW_LINE s = s [ : : - 1 ] NEW_LINE cur = 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT val += ( ord ( s [ i ] ) - ord ( '0' ) ) * cur NEW_LINE cur *= 10 NEW_LINE DEDENT return val NEW_LINE DEDENT def generate ( s , len1 , uniq ) : NEW_LINE INDENT if ( len ( s ) == len1 ) : NEW_LINE INDENT if ( check ( convert ( s ) ) ) : NEW_LINE INDENT uniq . add ( convert ( s ) ) NEW_LINE DEDENT return NEW_LINE DEDENT for i in range ( 4 ) : NEW_LINE INDENT generate ( s + chr ( i + ord ( '0' ) ) , len1 , uniq ) NEW_LINE DEDENT DEDENT def totalNumbers ( L , R ) : NEW_LINE INDENT ans = 0 NEW_LINE max_len = int ( log10 ( R ) ) + 1 NEW_LINE uniq = set ( ) NEW_LINE for i in range ( 1 , max_len + 1 , 1 ) : NEW_LINE INDENT generate ( " " , i , uniq ) NEW_LINE DEDENT for x in uniq : NEW_LINE INDENT if ( x >= L and x <= R ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 22 NEW_LINE R = 22 NEW_LINE print ( totalNumbers ( L , R ) ) NEW_LINE DEDENT