Sum of M maximum distinct digit sum from 1 to N that are factors of K | Java 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
import java . util . * ; class GFG { public static Vector < Integer > findFactors ( int n , int k ) { Vector < Integer > factors = new Vector < Integer > ( ) ; for ( int i = 1 ; i <= Math . sqrt ( k ) ; i ++ ) { if ( k % i == 0 ) { if ( k / i == i && i <= n ) factors . add ( i ) ; else { if ( i <= n ) factors . add ( i ) ; if ( k / i <= n ) factors . add ( k / i ) ; } } } return factors ; } public static Vector < Integer > findDigitSum ( Vector < Integer > a ) { for ( int i = 0 ; i < a . size ( ) ; i ++ ) { int c = 0 ; while ( a . get ( i ) > 0 ) { c += ( a . get ( i ) % 10 ) ; a . set ( i , ( a . get ( i ) / 10 ) ) ; } a . set ( i , c ) ; } return a ; } public static int findMMaxDistinctDigitSum ( Vector < Integer > distinctDigitSum , int m ) { int sum = 0 ; for ( int i = distinctDigitSum . size ( ) - 1 ; i >= 0 && m > 0 ; i -- , m -- ) sum += distinctDigitSum . get ( i ) ; return sum ; } public static int findDistinctMnumbers ( int n , int k , int m ) { Vector < Integer > factors = findFactors ( n , k ) ; Vector < Integer > digitSum = findDigitSum ( factors ) ; Collections . sort ( digitSum ) ; HashSet < Integer > hs1 = new HashSet < Integer > ( digitSum ) ; Vector < Integer > vect2 = new Vector < Integer > ( hs1 ) ; return findMMaxDistinctDigitSum ( vect2 , m ) ; } public static void main ( String args [ ] ) { int n = 100 , k = 80 , m = 4 ; System . out . println ( findDistinctMnumbers ( n , k , m ) ) ; } }