Sum of M maximum distinct digit sum from 1 to N that are factors of K | C ++ implementation to find the sum of maximum distinct digit sum of at most M numbers 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findFactors ( int n , int k ) { vector < int > factors ; for ( int i = 1 ; i <= sqrt ( k ) ; i ++ ) { if ( k % i == 0 ) { if ( k / i == i && i <= n ) factors . push_back ( i ) ; else { if ( i <= n ) factors . push_back ( i ) ; if ( k / i <= n ) factors . push_back ( k / i ) ; } } } return factors ; } vector < int > findDigitSum ( vector < int > a ) { for ( int i = 0 ; i < a . size ( ) ; i ++ ) { int c = 0 ; while ( a [ i ] > 0 ) { c += a [ i ] % 10 ; a [ i ] = a [ i ] / 10 ; } a [ i ] = c ; } return a ; } int findMMaxDistinctDigitSum ( vector < int > distinctDigitSum , int m ) { int sum = 0 ; for ( int i = distinctDigitSum . size ( ) - 1 ; i >= 0 && m > 0 ; i -- , m -- ) sum += distinctDigitSum [ i ] ; return sum ; } int findDistinctMnumbers ( int n , int k , int m ) { vector < int > factors = findFactors ( n , k ) ; vector < int > digitSum = findDigitSum ( factors ) ; sort ( digitSum . begin ( ) , digitSum . end ( ) ) ; vector < int > :: iterator ip ; ip = unique ( digitSum . begin ( ) , digitSum . end ( ) ) ; digitSum . resize ( distance ( digitSum . begin ( ) , ip ) ) ; return findMMaxDistinctDigitSum ( digitSum , m ) ; } int main ( ) { int n = 100 , k = 80 , m = 4 ; cout << findDistinctMnumbers ( n , k , m ) << endl ; return 0 ; }