# Count of n digit numbers whose sum of digits equals to given sum in C++

C++Server Side ProgrammingProgramming

Given a positive number as the number of digits and a sum. The goal is to find all d digit numbers that have sum of digits equal to the input sum. The numbers having leading zeros will not be considered as d digit numbers.

The ranges are digits between 1 to 100 and sum between 1 and 500.

## Let us understand with examples.

For Example

Input - digits = 3, digi_sum = 3

Output - Count of n digit numbers whose sum of digits equals to given sum are: 6

Explanation - Three digit numbers having sum of digits as 3 are:

102, 111, 120, 201, 210, and 300.

Input -  digits = 4  digi_sum = 2

Output - Count of n digit numbers whose sum of digits equals to given sum are: 4

Explanation - Four digit numbers having sum of digits as 2 are :

1001, 1010, 1100, and 2000.

## Approach used in the below program is as follows

In this approach we will traverse from the first d digit number and find the first number whose sum of digits is equal to the given sum. Then increment numbers by 9 until we find the sum of digits more than the given sum. Once a number having digit sum greater than input sum is found then increment the number by 1 and find the next number with sum as input sum. Repeat this process till the last d digit number.

• Take the number of digits and sum of digits as input.
• Function digits_sum(int digits, int digi_sum) takes both input values and returns the count of n digit numbers whose sum of digits equals a given sum.
• Take the initial count as 0.
• Take the first number as Left = pow(10, digits - 1). And the last number of the range as right = pow(10, digits) - 1 ( i.e  10 and 99 for digits=2 ).
• Using a while loop traverse from left to right.
• Take first=0 and last=i.
• For each i ( last ), take the rightmost digit ( last % 10 ) and add to first. Reduce last by 10 for the next iteration.
• If first becomes equal to digi_sum then increment count and update i by 9 for next iteration.
• Otherwise increment i by 1.
• At the end of all loops we will have count as numbers that have digit sum equal to digi_sum.
• Return count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

int digits_sum(int digits, int digi_sum) {
int count = 0;
int Left = pow(10, digits - 1);
int right = pow(10, digits) - 1;
int i = Left;
while (i <= right) {
int first = 0;
int last = i;
while (last != 0) {
first = first + last % 10;
last = last / 10;
}
if (first == digi_sum) {
count++;
i = i + 9;
} else {
i++;
}
}
return count;
}
int main() {
int digits = 5;
int digi_sum = 7;
cout << "Count of n digit numbers whose sum of digits equals to given sum are: " << digits_sum(digits, digi_sum);
return 0;
}

If we run the above code it will generate the following output −

## Output

Count of n digit numbers whose sum of digits equals to given sum are: 5