Length of longest subsequence having sum of digits of each element as a Composite Number | Python3 implementation of the above approach ; Function to generate prime numbers using Sieve of Eratosthenes ; Set 0 and 1 as non - prime ; If p is a prime ; Set all multiples of p as non - prime ; Function to find the digit sum of a given number ; Stores the sum of digits ; Extract digits and add to the sum ; Return the sum of the digits ; Function to find the longest subsequence with sum of digits of each element equal to a composite number ; Calculate sum of digits of current array element ; If sum of digits equal to 1 ; If sum of digits is a prime ; Driver Code ; Function call
N = 100005 NEW_LINE def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= p_size : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , p_size + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def digitSum ( number ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( number > 0 ) : NEW_LINE INDENT sum += ( number % 10 ) NEW_LINE number //= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def longestCompositeDigitSumSubsequence ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE prime = [ True ] * ( N + 1 ) NEW_LINE SieveOfEratosthenes ( prime , N ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT res = digitSum ( arr [ i ] ) NEW_LINE if ( res == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( not prime [ res ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 13 , 55 , 7 , 3 , 5 , 1 , 10 , 21 , 233 , 144 , 89 ] NEW_LINE n = len ( arr ) NEW_LINE longestCompositeDigitSumSubsequence ( arr , n ) NEW_LINE DEDENT