Sum of M maximum distinct digit sum from 1 to N that are factors of K | Function to find the factors of K in N ; Initialise a vector ; Find out the factors of K less than N ; Find the digit sum of each factor ; Sum of digits for each element in vector ; Find the largest M distinct digit sum from the digitSum vector ; Find the sum of last M numbers . ; Find the at most M numbers from N natural numbers whose digit sum is distinct and those M numbers are factors of K . ; Find out the factors of K less than N ; Sum of digits for each element in vector ; Sorting the digitSum vector ; Removing the duplicate elements ; " HashSet " is stores only unique elements ; Finding the sum and returning it ; Driver Code ; Function Call
function findFactors ( n , k ) { let factors = [ ] ; for ( let i = 1 ; i <= Math . sqrt ( k ) ; i ++ ) { if ( k % i == 0 ) { if ( k / i == i && i <= n ) factors . push ( i ) ; else { if ( i <= n ) factors . push ( i ) ; if ( k / i <= n ) factors . push ( k / i ) ; } } } return factors ; } function findDigitSum ( a ) { for ( let i = 0 ; i < a . length ; i ++ ) { let c = 0 ; while ( a [ i ] > 0 ) { c += ( a [ i ] % 10 ) ; a [ i ] = Math . floor ( a [ i ] / 10 ) ; } a [ i ] = c ; } return a ; } function findMMaxDistinctDigitSum ( distinctDigitSum , m ) { let sum = 0 ; for ( let i = distinctDigitSum . length - 1 ; i >= 0 && m > 0 ; i -- , m -- ) sum += distinctDigitSum [ i ] ; return sum ; } function findDistinctMnumbers ( n , k , m ) { let factors = findFactors ( n , k ) ; let digitSum = findDigitSum ( factors ) ; digitSum . sort ( function ( a , b ) { return a - b ; } ) ; let hs1 = new Set ( digitSum ) ; let vect2 = Array . from ( hs1 ) ; return findMMaxDistinctDigitSum ( vect2 , m ) ; } let n = 100 , k = 80 , m = 4 ; document . write ( findDistinctMnumbers ( n , k , m ) ) ;