Length of longest subsequence having sum of digits of each element as a Composite Number | Javascript 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
let N = 100005 ; function SieveOfEratosthenes ( prime , p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( let p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( let i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } function digitSum ( number ) { let sum = 0 ; while ( number > 0 ) { sum += ( number % 10 ) ; number = Math . floor ( number / 10 ) ; } return sum ; } function longestCompositeDigitSumSubsequence ( arr , n ) { let count = 0 ; let prime = new Array ( N + 1 ) ; for ( let i = 0 ; i <= N ; i ++ ) prime [ i ] = true ; SieveOfEratosthenes ( prime , N ) ; for ( let i = 0 ; i < n ; i ++ ) { let res = digitSum ( arr [ i ] ) ; if ( res == 1 ) { continue ; } if ( prime [ res ] == false ) { count ++ ; } } document . write ( count ) ; } let arr = [ 13 , 55 , 7 , 3 , 5 , 1 , 10 , 21 , 233 , 144 , 89 ] ; let n = arr . length ; longestCompositeDigitSumSubsequence ( arr , n ) ;