Count of n digit numbers whose sum of digits equals to given sum
Last Updated :
23 Jul, 2025
Given two integers n and sum, the task is to find the count of all n digit numbers with sum of digits equal to sum.
Note: Leading 0's are not counted as digits. If there exist no n digit number with sum of digits equal to given sum, print -1.
Example:
Input: n = 2, sum= 2
Output: 2
Explanation: The numbers are 11 and 20
Input: n = 2, sum= 5
Output: 5
Explanation: The numbers are 14, 23, 32, 41 and 50
[Naive Approach - 1] - Using Recursion - O(n*(9^n)) Time and O(n) Space
The idea is to find all n-digit numbers where the sum of digits equals the sum. It uses recursion to try every digit from 0 to 9 for each position, reducing the given sum at each step. The first digit is taken from 1 to 9 to ensure valid n-digit numbers. The recursion stops when there are no digits left, checking if the sumbecomes zero.
C++
// A C++ program to count numbers with sum of
// digits as a given target using Recursion.
#include <bits/stdc++.h>
using namespace std;
// Recursive function to count n-digit numbers
// with sum of digits as the target.
int countRec(int n, int sum) {
// Base case: If there are no digits left,
// check if the target is also zero.
if (n == 0) {
return sum == 0;
}
// If the target becomes zero,
// there's exactly one valid number.
if (sum == 0) {
return 1;
}
int ans = 0;
// Traverse through digits 0-9 to calculate
// the count of numbers recursively.
for (int i = 0; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(n - 1, sum - i);
}
}
return ans;
}
// Function to count n-digit numbers
// with sum of digits as the target.
int countWays(int n, int sum) {
int ans = 0;
// Traverse through digits 1-9 as the first
// digit cannot be zero for n-digit numbers.
for (int i = 1; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(n - 1, sum - i);
}
}
if(ans == 0) return -1;
return ans;
}
int main() {
int n = 2;
int sum = 5;
int ans = countWays(n, sum);
cout<<ans;
return 0;
}
Java
// A Java program to count numbers with sum of
// digits as a given target using Recursion.
import java.util.*;
class GfG {
// Recursive function to count n-digit numbers
// with sum of digits as the target.
static int countRec(int n, int sum) {
// Base case: If there are no digits left,
// check if the target is also zero.
if (n == 0) {
return sum == 0 ? 1 : 0;
}
// If the target becomes zero,
// there's exactly one valid number.
if (sum == 0) {
return 1;
}
int ans = 0;
// Traverse through digits 0-9 to calculate
// the count of numbers recursively.
for (int i = 0; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(n - 1, sum - i);
}
}
return ans;
}
// Function to count n-digit numbers
// with sum of digits as the target.
static int countWays(int n, int sum) {
int ans = 0;
// Traverse through digits 1-9 as the first
// digit cannot be zero for n-digit numbers.
for (int i = 1; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(n - 1, sum - i);
}
}
if(ans == 0) return -1;
return ans;
}
public static void main(String[] args) {
int n = 2;
int sum = 5;
int ans = countWays(n, sum);
System.out.println(ans);
}
}
Python
# A Python program to count numbers with sum of
# digits as a given target using Recursion.
def countRec(n, sum):
# Base case: If there are no digits left,
# check if the target is also zero.
if n == 0:
return 1 if sum == 0 else 0
# If the target becomes zero,
# there's exactly one valid number.
if sum == 0:
return 1
ans = 0
# Traverse through digits 0-9 to calculate
# the count of numbers recursively.
for i in range(10):
if sum - i >= 0:
ans += countRec(n - 1, sum - i)
return ans
# Function to count n-digit numbers
# with sum of digits as the target.
def countWays(n, sum):
ans = 0
# Traverse through digits 1-9 as the first
# digit cannot be zero for n-digit numbers.
for i in range(1, 10):
if sum - i >= 0:
ans += countRec(n - 1, sum - i)
if(ans == 0):
return -1;
return ans
if __name__ == "__main__":
n = 2
sum = 5
ans = countWays(n, sum)
print(ans)
C#
// A C# program to count numbers with sum of
// digits as a given target using Recursion.
using System;
class GfG {
// Recursive function to count n-digit numbers
// with sum of digits as the target.
static int CountRec(int n, int sum) {
// Base case: If there are no digits left,
// check if the target is also zero.
if (n == 0) {
return sum == 0 ? 1 : 0;
}
// If the target becomes zero,
// there's exactly one valid number.
if (sum == 0) {
return 1;
}
int ans = 0;
// Traverse through digits 0-9 to calculate
// the count of numbers recursively.
for (int i = 0; i <= 9; i++) {
if (sum - i >= 0) {
ans += CountRec(n - 1, sum - i);
}
}
return ans;
}
// Function to count n-digit numbers
// with sum of digits as the target.
static int CountWays(int n, int sum) {
int ans = 0;
// Traverse through digits 1-9 as the first
// digit cannot be zero for n-digit numbers.
for (int i = 1; i <= 9; i++) {
if (sum - i >= 0) {
ans += CountRec(n - 1, sum - i);
}
}
if(ans == 0) return -1;
return ans;
}
public static void Main(string[] args) {
int n = 2;
int sum = 5;
int ans = CountWays(n, sum);
Console.WriteLine(ans);
}
}
JavaScript
// A Javascript program to count numbers with sum of
// digits as a given target using Recursion.
function countRec(n, sum) {
// Base case: If there are no digits left,
// check if the target is also zero.
if (n === 0) {
return sum === 0 ? 1 : 0;
}
// If the target becomes zero,
// there's exactly one valid number.
if (sum === 0) {
return 1;
}
let ans = 0;
// Traverse through digits 0-9 to calculate
// the count of numbers recursively.
for (let i = 0; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(n - 1, sum - i);
}
}
return ans;
}
// Function to count n-digit numbers
// with sum of digits as the target.
function countWays(n, sum) {
let ans = 0;
// Traverse through digits 1-9 as the first
// digit cannot be zero for n-digit numbers.
for (let i = 1; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(n - 1, sum - i);
}
}
if(ans == 0) return -1;
return ans;
}
const n = 2;
const sum = 5;
const ans = countWays(n, sum);
console.log(ans);
Time Complexity: O(n * (9 ^ n)) , for each of the n digits, we are exploring all other possible 9 digits.
Space Complexity: O(n), considering the recursive stack.
[Naive Approach - 2] - Using Iterative Approach - O(n*10^n) Time and O(1) Space
To count all n-digit numbers whose sum of digits equals a given target sum, we iterate through each number within the range of n-digit numbers. For each number, we calculate the sum of its digits. If the sum matches the given sum, we increment the count. While we considered optimizing the process by incrementing by 9 after finding a valid number, this step could skip some valid numbers where the sum of digits changes slightly. Therefore, it's safer to increment by 1 and check all possible numbers in the range to ensure no valid numbers are missed. Finally, we return the total count of numbers with the desired sum of digits.
Below is given the implementation:
C++
// C++ program to count n-digit numbers with
// the sum of digits as the target using iteration.
#include <bits/stdc++.h>
using namespace std;
int countWays(int n, int sum) {
// Calculate the range for n-digit numbers
int start = pow(10, n - 1);
int end = pow(10, n) - 1;
int count = 0;
int i = start;
// Iterate through all n-digit numbers
while (i <= end) {
int currentSum = 0;
int temp = i;
// Calculate the sum of digits of the number
while (temp != 0) {
currentSum += temp % 10;
temp /= 10;
}
// Check if the sum of digits matches the target
if (currentSum == sum) {
count++;
i += 9;
} else {
i++;
}
}
if(count == 0) return -1;
return count;
}
int main() {
int n = 2;
int sum = 5;
int ans = countWays(n, sum);
cout<<ans;
return 0;
}
Java
// Java program to count n-digit numbers with
// the sum of digits as a given target
// using iteration.
class GfG {
// Function to count n-digit numbers with
// the sum of digits as the target.
static int countWays(int n, int sum) {
// Calculate the range for n-digit numbers.
int start = (int) Math.pow(10, n - 1);
int end = (int) Math.pow(10, n) - 1;
int count = 0;
int i = start;
// Iterate through all n-digit numbers.
while (i <= end) {
int currentSum = 0;
int temp = i;
// Calculate the sum of digits of the number.
while (temp != 0) {
currentSum += temp % 10;
temp /= 10;
}
// Check if the sum of digits matches the target.
if (currentSum == sum) {
count++;
i += 9;
} else {
i++;
}
}
if(count == 0) return -1;
return count;
}
public static void main(String[] args) {
int n = 2;
int sum = 5;
int ans = countWays(n, sum);
System.out.println(ans);
}
}
Python
# Python program to count n-digit numbers with
# the sum of digits as the target using iteration.
# Function to count n-digit numbers with the
# sum of digits as the target using iteration.
def countWays(n, sum):
# Calculate the range for n-digit numbers.
start = 10 ** (n - 1)
end = 10 ** n - 1
count = 0
i = start
# Iterate through all n-digit numbers.
while i <= end:
current_sum = 0
temp = i
# Calculate the sum of digits of the number.
while temp != 0:
current_sum += temp % 10
temp //= 10
# Check if the sum of digits matches the target.
if current_sum == sum:
count += 1
i += 9
else:
i += 1
if(count == 0):
return -1;
return count
if __name__ == "__main__":
n = 2
sum = 5
ans = countWays(n, sum)
print(ans)
C#
// C# program to count n-digit numbers with
// the sum of digits as the target using iteration.
using System;
class GfG {
// Function to count n-digit numbers
// with sum of digits as the target.
static int countWays(int n, int sum) {
// Calculate the range for n-digit numbers.
int start = (int)Math.Pow(10, n - 1);
int end = (int)Math.Pow(10, n) - 1;
int count = 0;
int i = start;
// Iterate through all n-digit numbers.
while (i <= end) {
int currentSum = 0;
int temp = i;
// Calculate the sum of digits of the number.
while (temp != 0) {
currentSum += temp % 10;
temp /= 10;
}
// Check if the sum of digits matches the target.
if (currentSum == sum) {
count++;
i += 9;
} else {
i++;
}
}
if(count == 0) return -1;
return count;
}
static void Main(string[] args) {
int n = 2;
int sum = 5;
int ans = countWays(n, sum);
Console.WriteLine(ans);
}
}
JavaScript
// Javascript program to count n-digit numbers with
// the sum of digits as the target using iteration.
// Function to count n-digit numbers
// with sum of digits as the target.
function countWays(n, sum) {
// Calculate the range for n-digit numbers.
const start = Math.pow(10, n - 1);
const end = Math.pow(10, n) - 1;
let count = 0;
let i = start;
// Iterate through all n-digit numbers.
while (i <= end) {
let currentSum = 0;
let temp = i;
// Calculate the sum of digits of the number.
while (temp !== 0) {
currentSum += temp % 10;
temp = Math.floor(temp / 10);
}
// Check if the sum of digits matches the target.
if (currentSum === sum) {
count++;
i += 9;
} else {
i++;
}
}
if(count == 0) return -1;
return count;
}
//driver code
const n = 2;
const sum = 5;
const ans = countWays(n, sum);
console.log(ans);
Time Complexity: O(n * 10^n), for each digit we are iterating through all possible 10 digits.
Space Complexity: O(1)
[Expected Approach] - Using Memoization - O(n * sum) Time and O(n * sum) Space
The idea is to count n-digit numbers with a sum of digits equal to the given sum using recursion with memoization to optimize repeated calculations. A 2d array memo[][] is used to store results for a given number of digits and given sum to avoid redundant computations. Starting from digits 1 to 9 for the first position, recursively explores all possible digits while reducing the given sum, ensuring efficiency by reusing previously computed results.
Below is given the implementation:
C++
// A C++ program to count numbers with sum of
// digits as a given target using Memoization.
#include <bits/stdc++.h>
using namespace std;
// Recursive function to count n-digit numbers
// with sum of digits as the target.
int countRec(int n, int sum,
vector<vector<int>> &memo) {
// Base case: If there are no digits left,
// check if the target is also zero.
if (n == 0) {
return sum == 0;
}
// If the target becomes zero,
// there's exactly one valid number.
if (sum == 0) {
return 1;
}
// Check if already computed
if (memo[n][sum] != -1) {
return memo[n][sum];
}
int ans = 0;
// Traverse through digits 0-9 to calculate
// the count of numbers recursively.
for (int i = 0; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(n - 1,
sum - i, memo);
}
}
// Store and return the result
return memo[n][sum] = ans;
}
// Function to count n-digit numbers
// with sum of digits as the target.
int countWays(int n, int sum) {
// Create a memoization table
vector<vector<int>> memo(n + 1,
vector<int>(sum + 1, -1));
int ans = 0;
// Traverse through digits 1-9 as the first
// digit cannot be zero for n-digit numbers.
for (int i = 1; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(n - 1, sum - i, memo);
}
}
if(ans == 0) return -1;
return ans;
}
int main() {
int n = 2;
int sum = 5;
int ans = countWays(n, sum);
cout<<ans;
return 0;
}
Java
// A Java program to count numbers with sum of
// digits as a given target using Memoization.
import java.util.*;
class GfG {
// Recursive function to count n-digit numbers
// with sum of digits as the target.
static int countRec(
int n, int sum, int[][] memo) {
// Base case: If there are no digits left,
// check if the target is also zero.
if (n == 0) {
return sum == 0 ? 1 : 0;
}
// If the target becomes zero,
// there's exactly one valid number.
if (sum == 0) {
return 1;
}
// If already computed, return the result.
if (memo[n][sum] != -1) {
return memo[n][sum];
}
int ans = 0;
// Traverse through digits 0-9 to calculate
// the count of numbers recursively.
for (int i = 0; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(
n - 1, sum - i, memo);
}
}
// Store and return the result.
return memo[n][sum] = ans;
}
// Function to count n-digit numbers
// with sum of digits as the target.
static int countWays(int n, int sum) {
// Create a memoization table.
int[][] memo = new int[n + 1]
[sum + 1];
// Initialize memo with -1 to indicate
// uncomputed states.
for (int[] row : memo) {
Arrays.fill(row, -1);
}
int ans = 0;
// Traverse through digits 1-9 as the first
// digit cannot be zero for n-digit numbers.
for (int i = 1; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(
n - 1, sum - i, memo);
}
}
if(ans == 0) return -1;
return ans;
}
public static void main(String[] args) {
int n = 2;
int sum = 5;
int ans = countWays(n, sum);
System.out.println(ans);
}
}
Python
# A Python program to count numbers with sum of
# digits as a given target using Memoization.
def countRec(n, sum, memo):
# Base case: If there are no digits left,
# check if the target is also zero.
if n == 0:
return 1 if sum == 0 else 0
# If the target becomes zero,
# there's exactly one valid number.
if sum == 0:
return 1
# If already computed, return the result.
if memo[n][sum] != -1:
return memo[n][sum]
ans = 0
# Traverse through digits 0-9 to calculate
# the count of numbers recursively.
for i in range(10):
if sum - i >= 0:
ans += countRec(n - 1, sum - i, memo)
# Store and return the result.
memo[n][sum] = ans
return ans
# Function to count n-digit numbers
# with sum of digits as the target.
def countWays(n, sum):
# Create a memoization table initialized to -1.
memo = [[-1] * (sum + 1) for _ in range(n + 1)]
ans = 0
# Traverse through digits 1-9 as the first
# digit cannot be zero for n-digit numbers.
for i in range(1, 10):
if sum - i >= 0:
ans += countRec(n - 1, sum - i, memo)
if(ans == 0):
return -1;
return ans
if __name__ == "__main__":
n = 2
sum = 5
ans = countWays(n, sum)
print(ans)
C#
// A C# program to count numbers with sum of
// digits as a given target using Memoization.
using System;
class GfG {
static int CountRec(int n, int sum, int[,] memo) {
// Base case: If there are no digits left,
// check if the target is also zero.
if (n == 0) {
return sum == 0 ? 1 : 0;
}
// If the target becomes zero,
// there's exactly one valid number.
if (sum == 0) {
return 1;
}
// If already computed, return the result.
if (memo[n, sum] != -1) {
return memo[n, sum];
}
int ans = 0;
// Traverse through digits 0-9 to calculate
// the count of numbers recursively.
for (int i = 0; i <= 9; i++) {
if (sum - i >= 0) {
ans += CountRec(n - 1, sum - i, memo);
}
}
// Store and return the result.
memo[n, sum] = ans;
return ans;
}
// Function to count n-digit numbers
// with sum of digits as the target.
static int CountWays(int n, int sum) {
// Initialize a memoization table with -1.
int[,] memo = new int[n + 1, sum + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= sum; j++) {
memo[i, j] = -1;
}
}
int ans = 0;
// Traverse through digits 1-9 as the first
// digit cannot be zero for n-digit numbers.
for (int i = 1; i <= 9; i++) {
if (sum - i >= 0) {
ans += CountRec(n - 1, sum - i, memo);
}
}
if(ans == 0) return -1;
return ans;
}
public static void Main(string[] args) {
int n = 2;
int sum = 5;
int ans = CountWays(n, sum);
Console.WriteLine(ans);
}
}
JavaScript
// A JavaScript program to count numbers with sum of
// digits as a given target using Memoization.
function countRec(n, sum, memo) {
// Base case: If there are no digits left,
// check if the target is also zero.
if (n === 0) {
return sum === 0 ? 1 : 0;
}
// If the target becomes zero,
// there's exactly one valid number.
if (sum === 0) {
return 1;
}
// If already computed, return the result.
if (memo[n][sum] !== -1) {
return memo[n][sum];
}
let ans = 0;
// Traverse through digits 0-9 to calculate
// the count of numbers recursively.
for (let i = 0; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(n - 1, sum - i, memo);
}
}
// Store and return the result.
memo[n][sum] = ans;
return ans;
}
// Function to count n-digit numbers
// with sum of digits as the target.
function countWays(n, sum) {
// Initialize a memoization table with -1.
const memo = Array.from({ length: n + 1 }, () =>
Array(sum + 1).fill(-1)
);
let ans = 0;
// Traverse through digits 1-9 as the first
// digit cannot be zero for n-digit numbers.
for (let i = 1; i <= 9; i++) {
if (sum - i >= 0) {
ans += countRec(n - 1, sum - i, memo);
}
}
if(ans == 0) return -1;
return ans;
}
//driver code
const n = 2;
const sum = 5;
const ans = countWays(n, sum);
console.log(ans);
Time Complexity: O(n * sum), for each of the n digits, we are considering the sum up to given sum.
Space Complexity: O(n * sum), to store the elements in memo.
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