Sum of M maximum distinct digit sum from 1 to N that are factors of K
Last Updated :
19 Jul, 2025
Given an array of natural numbers upto N and two numbers M and K, the task is to find the sum of M maximum distinct digit sum M numbers from N natural numbers which are factors of K.
Examples:
Input: N = 50, M = 4, K = 30
Output: 16
Explanation:
From 1 to 50, factors of 30 = {1, 2, 3, 5, 6, 10, 15, 30}.
Digit sum of every factor = {1, 2, 3, 5, 6, 1, 6, 3}.
4 largest digit sum = 2, 3, 5, 6.
Sum = 16
Input: N = 5, M = 3, K = 74
Output: 3
Explanation:
From 1 to 5 factors of 74 = {1, 2}
Digit sum of every factor = {1, 2}.
3 largest digit sum = 1, 2 (Here only 2 such numbers are present. But it is asked for atmost M. So these 2 will be considered only.)
Sum = 3
Naive Approach: Simple solution is to run the loop from 1 to N and find the list of all numbers that perfectly divides K. Find the digit sum of each factor and sort them in descending order and print M distinct elements from this list from top.
Efficient Approach:
- Find all the factors of K in the range of 1 to N by iterating from 2 to ?K such that the element completely divides the number. For Detailed Explanation of this approach please refer this article and store them in an array.
- Find the digit sum of the numbers stored in the factors array.
For Example:
For the Given Array - {4, 10, 273 }
Digit Sum of the Elements -
Element 0 Digit Sum - "4" = 4
Element 1 Digit Sum - "10" = 1 + 0 = 10
Element 2 Digit Sum - "273" = 2 + 7 + 3 = 12
- Remove duplicates from the digit sum as we need distinct elements.
- Sort the distinct digit sums in reverse order and find the sum of first at most M elements out of this digit-sum array.
Below is the implementation of the above approach.
C++
// 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
#include <bits/stdc++.h>
using namespace std;
// Function to find the factors
// of K in N
vector<int> findFactors(int n, int k)
{
// Initialise a vector
vector<int> factors;
// Find out the factors of
// K less than N
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;
}
// Find the digit sum of each factor
vector<int> findDigitSum(vector<int> a)
{
// Sum of digits for each
// element in vector
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;
}
// Find the largest M distinct digit
// sum from the digitSum vector
int findMMaxDistinctDigitSum(
vector<int> distinctDigitSum,
int m)
{
// Find the sum of last M numbers.
int sum = 0;
for (int i = distinctDigitSum.size() - 1;
i >= 0 && m > 0;
i--, m--)
sum += distinctDigitSum[i];
return sum;
}
// Find the at most M numbers from N natural
// numbers whose digit sum is distinct
// and those M numbers are factors of K.
int findDistinctMnumbers(int n, int k, int m)
{
// Find out the factors of
// K less than N
vector<int> factors = findFactors(n, k);
// Sum of digits for each
// element in vector
vector<int> digitSum = findDigitSum(factors);
// Sorting the digitSum vector
sort(digitSum.begin(), digitSum.end());
// Removing the duplicate elements
vector<int>::iterator ip;
ip = unique(digitSum.begin(), digitSum.end());
digitSum.resize(distance(
digitSum.begin(),
ip));
// Finding the sum and returning it
return findMMaxDistinctDigitSum(digitSum, m);
}
// Driver Code
int main()
{
int n = 100, k = 80, m = 4;
// Function Call
cout
<< findDistinctMnumbers(n, k, m)
<< endl;
return 0;
}
Java
// 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
import java.util.*;
class GFG
{
// Function to find the factors
// of K in N
public static Vector<Integer> findFactors(int n, int k)
{
Vector<Integer> factors = new Vector<Integer>();
// Initialise a vector
// Find out the factors of
// K less than N
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;
}
// Find the digit sum of each factor
public static Vector<Integer> findDigitSum(Vector<Integer> a)
{
// Sum of digits for each
// element in vector
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;
}
// Find the largest M distinct digit
// sum from the digitSum vector
public static int findMMaxDistinctDigitSum(Vector<Integer> distinctDigitSum,int m)
{
// Find the sum of last M numbers.
int sum = 0;
for (int i = distinctDigitSum.size() - 1;
i >= 0 && m > 0;i--, m--)
sum += distinctDigitSum.get(i);
return sum;
}
// Find the at most M numbers from N natural
// numbers whose digit sum is distinct
// and those M numbers are factors of K.
public static int findDistinctMnumbers(int n, int k, int m)
{
// Find out the factors of
// K less than N
Vector<Integer> factors = findFactors(n, k);
// Sum of digits for each
// element in vector
Vector<Integer> digitSum = findDigitSum(factors);
// Sorting the digitSum vector
Collections.sort(digitSum);
// Removing the duplicate elements
HashSet<Integer> hs1 = new HashSet<Integer>(digitSum);
//"HashSet" is stores only unique elements
Vector<Integer> vect2 = new Vector<Integer>(hs1);
// Finding the sum and returning it
return findMMaxDistinctDigitSum(vect2, m);
}
// Driver Code
public static void main(String args[])
{
int n = 100, k = 80, m = 4;
// Function Call
System.out.println(findDistinctMnumbers(n, k, m));
}
}
// This code is contributed by SoumikMondal
Python3
# Python 3 implementation to find the sum of
# maximum distinct digit sum of at most
# M numbers from 1 to N that are factors of K
import math
# Function to find the factors
# of K in N
def findFactors(n, k):
# Initialise a vector
factors = []
# Find out the factors of
# K less than N
sqt = (int)(math.sqrt(k))
for i in range(1, sqt):
if (k % i == 0):
if (k // i == i and i <= n):
factors.append(i)
else:
if (i <= n):
factors.append(i)
if (k // i <= n):
factors.append(k // i)
return factors
# Find the digit sum of each factor
def findDigitSum(a):
# Sum of digits for each
# element in vector
for i in range(len(a)):
c = 0
while (a[i] > 0):
c += a[i] % 10
a[i] = a[i] // 10
a[i] = c
return a
# Find the largest M distinct digit
# sum from the digitSum vector
def findMMaxDistinctDigitSum(
distinctDigitSum, m):
# Find the sum of last M numbers.
sum = 0
i = len(distinctDigitSum) - 1
while (i >= 0 and m > 0):
sum += distinctDigitSum[i]
i -= 1
m -= 1
return sum
# Find the at most M numbers from N natural
# numbers whose digit sum is distinct
# and those M numbers are factors of K
def findDistinctMnumbers(n, k, m):
# Find out the factors of
# K less than N
factors = findFactors(n, k)
# Sum of digits for each
# element in vector
digitSum = findDigitSum(factors)
# Sorting the digitSum vector
digitSum.sort()
# Removing the duplicate elements
ip = list(set(digitSum))
# Finding the sum and returning it
return findMMaxDistinctDigitSum(ip, m)
# Driver Code
if __name__ == "__main__":
n = 100
k = 80
m = 4
# Function Call
print(findDistinctMnumbers(n, k, m))
# This code is contributed by chitranayal
C#
// Include namespace system
using System;
using System.Collections.Generic;
public class GFG
{
// Function to find the factors
// of K in N
public static List<int> findFactors(int n, int k)
{
var factors = new List<int>();
// Initialise a vector
// Find out the factors of
// K less than N
for (int i = 1; i <= Math.Sqrt(k); i++)
{
if (k % i == 0)
{
if ((int)(k / i) == i && i <= n)
{
factors.Add(i);
}
else
{
if (i <= n)
{
factors.Add(i);
}
if ((int)(k / i) <= n)
{
factors.Add((int)(k / i));
}
}
}
}
return factors;
}
// Find the digit sum of each factor
public static List<int> findDigitSum(List<int> a)
{
// Sum of digits for each
// element in vector
for (int i = 0; i < a.Count; i++)
{
var c = 0;
while (a[i] > 0)
{
c += (a[i] % 10);
a[i] = ((int)(a[i] / 10));
}
a[i] = c;
}
return a;
}
// Find the largest M distinct digit
// sum from the digitSum vector
public static int findMMaxDistinctDigitSum(List<int> distinctDigitSum, int m)
{
// Find the sum of last M numbers.
var sum = 0;
for (int i = distinctDigitSum.Count - 1; i >= 0 && m > 0; i--, m--)
{
sum += distinctDigitSum[i];
}
return sum;
}
// Find the at most M numbers from N natural
// numbers whose digit sum is distinct
// and those M numbers are factors of K.
public static int findDistinctMnumbers(int n, int k, int m)
{
// Find out the factors of
// K less than N
var factors = GFG.findFactors(n, k);
// Sum of digits for each
// element in vector
var digitSum = GFG.findDigitSum(factors);
// Sorting the digitSum vector
digitSum.Sort();
// Removing the duplicate elements
var hs1 = new HashSet<int>(digitSum);
// "HashSet" is stores only unique elements
var vect2 = new List<int>(hs1);
// Finding the sum and returning it
return GFG.findMMaxDistinctDigitSum(vect2, m);
}
// Driver Code
public static void Main(String[] args)
{
var n = 100;
var k = 80;
var m = 4;
// Function Call
Console.WriteLine(GFG.findDistinctMnumbers(n, k, m));
}
}
// This code is contributed by aadityaburujwale.
JavaScript
<script>
// Javascript 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
function findFactors(n, k)
{
let factors = [];
// Initialise a vector
// Find out the factors of
// K less than N
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;
}
// Find the digit sum of each factor
function findDigitSum(a)
{
// Sum of digits for each
// element in vector
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;
}
// Find the largest M distinct digit
// sum from the digitSum vector
function findMMaxDistinctDigitSum(distinctDigitSum, m)
{
// Find the sum of last M numbers.
let sum = 0;
for(let i = distinctDigitSum.length - 1;
i >= 0 && m > 0;i--, m--)
sum += distinctDigitSum[i];
return sum;
}
// Find the at most M numbers from N natural
// numbers whose digit sum is distinct
// and those M numbers are factors of K.
function findDistinctMnumbers(n, k, m)
{
// Find out the factors of
// K less than N
let factors = findFactors(n, k);
// Sum of digits for each
// element in vector
let digitSum = findDigitSum(factors);
// Sorting the digitSum vector
digitSum.sort(function(a, b){return a - b;});
// Removing the duplicate elements
let hs1 = new Set(digitSum);
// "HashSet" is stores only unique elements
let vect2 = Array.from(hs1);
// Finding the sum and returning it
return findMMaxDistinctDigitSum(vect2, m);
}
// Driver Code
let n = 100, k = 80, m = 4;
// Function Call
document.write(findDistinctMnumbers(n, k, m));
// This code is contributed by rag2127
</script>
Performance Analysis:
- Time Complexity: In the given approach, there are mainly two process which is as follows -
- Time Complexity to find the factors of a number is: O(?(K))
- Time complexity to sort and store the unique elements: O(?(K)log(?(K)))
- Auxiliary Space: In the given approach there is an extra array used to store the factors of the number K, which is: O(?(K))
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem