Print all n-digit numbers whose sum of digits equals to given sum in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two numbers n and sum. We have to print all n digit numbers whose sum is equal to the sum. In this problem, numbers with leading 0’s are not considered.

Let’s take an example to understand the problem,

Input: n = 2 , sum = 5
Output: 14 23 32 41 50
Explanation: The sum of digits of the number in all numbers in 5.

To solve this problem, we will have to find all the n-digit numbers with sum with the given sum value. For this, we will fix a digit place with all values and based on its position to be even or odd, call for values at other places in the number such that the condition remains satisfied.

Example

Program to implement the above solution −

 Live Demo

#include <iostream>
using namespace std;
void PrintNumberWithDigitSum(int n, int sum, char* out, int index) {
   if (index > n || sum < 0)
      return;
   if (index == n) {
      if(sum == 0) {
         out[index] = ' ';
         cout << out << " ";
      }
      return;
   }
   for (int i = 0; i <= 9; i++) {
      out[index] = i + '0';
      PrintNumberWithDigitSum(n, sum - i, out, index + 1);
   }
}
void numberWithSum(int n, int sum) {
   char out[n + 1];
   for (int i = 1; i <= 9; i++) {
      out[0] = i + '0';
      PrintNumberWithDigitSum(n, sum - i, out, 1);
   }
}
int main() {
   int n = 3, sum = 6;
   cout<<"All "<<n<<" digit numbers with sum "<<sum<<" are :\n";
   numberWithSum(n, sum);
   return 0;
}

Output

All 3 digit numbers with sum 6 are −
105 114 123 132 141 150 204 213 222 231 240 303 312 321 330 402 411 420 501 510 600
raja
Published on 22-Jan-2020 15:11:35
Advertisements