Find numbers whose sum of digits equals a value

Data StructureDynamic ProgrammingAlgorithms

There are a number n and a value. We have to find all n digit numbers, where the sum of all n digit the s is the same as the given value. Here 0 is noa t counted as a digit.

The number n must be in the range 1 to 100, and value must be in range 1 to 500.

Input and Output

This algorithm takes number of digits, and the sum value.
Let the digit count is 3. and sum is 15.
Display the number of different 3-digit numbers whose sum is 15.
The result is 69. (There are 69 different 3-digit numbers whose sum is 15)


count(digit, sum)

Input: Digit of numbers, given value.

Output: Count how many numbers.

   if digit = 0, then
      return true when sum = 0

   if memTable[digit, sum] is not vacant, then
      return memTable[digit, sum]
   answer := 0

   for i := 0 to 9 do
      if sum – i >= 0, then
         answer := answer + count(digit – 1, sum - i)

   return memTable[digit, sum] := answer

numberCount(digit, sum)

Input: Digits of number, the given value.

Output: How many numbers of that type of number.

   define memTable and make all space vacant
   res := 0

   for i := 1 to 9, do
      if sum – i >= 0, then
         res := res + count(digit – 1, sum - i)

   return result


#define ROW 101
#define COL 501
using namespace std;

unsigned long long int memTable[ROW][COL];

unsigned long long int count(int digit, int sum) {
   if (digit == 0)    //for 0 digit number check if the sum is 0 or not
      return sum == 0;

   if (memTable[digit][sum] != -1)    //when subproblem has found the result, return it
      return memTable[digit][sum];

   unsigned long long int ans = 0;    //set the answer to 0 for first time

   for (int i=0; i<10; i++)    //count for each digit and find numbers starting with it
      if (sum-i >= 0)
         ans += count(digit-1, sum-i);
   return memTable[digit][sum] = ans;

unsigned long long int numberCount(int digit, int sum) {
   for(int i = 0; i<ROW; i++)    //initially all entries of memorization table is -1
      for(int j = 0; j<ROW; j++)
         memTable[i][j] = -1;
   unsigned long long int result = 0;
   for (int i = 1; i <= 9; i++)    //count for each digit and find numbers starting with it
      if (sum-i >= 0)
         result += count(digit-1, sum-i);
   return result;

int main() {
   int digit, sum;
   cout << "Enter digit count: "; cin >> digit;
   cout << "Enter Sum: "; cin >> sum;
   cout << "Number of values: " << numberCount(digit, sum);


Enter digit count: 3
Enter Sum: 15
Number of values: 69
Updated on 16-Jun-2020 14:28:01