Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count N digits numbers with sum divisible by K

  • Last Updated : 31 Oct, 2021

Given two integers N and K, the task is to count all N digits numbers whose sum of digits is divisible by K.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

 Input: N = 2, K = 7
Output: 12
Explanation: 2 digits numbers with sum divisible by 7 are: {16, 25, 34, 43, 52, 59, 61, 68, 70, 77, 86, 95}.
Therefore, the required output is 12.

Input: N = 1, K = 2
Output: 4



Naive Approach: The simplest approach is to traverse all the numbers from the range [10(N – 1), 10N – 1] and check if the sum of all the digits of a number that lies within the range is divisible by K or not. For every number for which the condition is found to be true, increase count. Finally, print the count.

Time Complexity: O(10N – 10N – 1 – 1)
Auxiliary Space: O(1)

Efficient Approach: The idea is to use Digit DP technique to optimize the above approach. Below is the recurrence relation:

CountNum(N, sum, st) = \sum^{9}_{i=0} countNum(N - 1, (sum + i)\mod K, st)
 

sum: represents sum of digits 
st: check if a number contains any leading 0. 
 

 

Follow the steps below to solve the problem:  

  1. Initialize a 3D array dp[N][K][st] to compute and store the values of all subproblems of the above recurrence relation.
  2. Finally, return the value of dp[N][sum%K][st].

C++




// C++ Program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
#define M 1000
 
// Function to count the N digit numbers
// whose sum is divisible by K
int countNum(int N, int sum, int K,
             bool st, int dp[M][M][2])
{
    // Base case
    if (N == 0 and sum == 0) {
        return 1;
    }
    if (N < 0) {
        return 0;
    }
 
    // If already computed
    // subproblem occurred
    if (dp[N][sum][st] != -1) {
        return dp[N][sum][st];
    }
 
    // Store the count of N digit numbers
    // whose sum is divisible by K
    int res = 0;
 
    // Check if the number does not contain
    // any leading 0.
    int start = st == 1 ? 0 : 1;
 
    // Recurrence relation
    for (int i = start; i <= 9; i++) {
        res += countNum(N - 1, (sum + i) % K,
                        K, (st | i > 0), dp);
    }
 
    return dp[N][sum][st] = res;
}
 
// Driver Code
int main()
{
    int N = 2, K = 7;
 
    // Stores the values of
    // overlapping subproblems
    int dp[M][M][2];
 
    memset(dp, -1, sizeof(dp));
 
    cout << countNum(N, 0, K, 0, dp);
}

Java




// Java program to implement
// the above approach
import java.util.*;
import java.lang.*;
 
class GFG {
 
    static final int M = 1000;
 
    // Function to count the N digit numbers
    // whose sum is divisible by K
    static int countNum(int N, int sum, int K,
                        int st, int dp[][][])
    {
 
        // Base case
        if (N == 0 && sum == 0) {
            return 1;
        }
        if (N < 0) {
            return 0;
        }
 
        // If already computed
        // subproblem occurred
        if (dp[N][sum][st] != -1) {
            return dp[N][sum][st];
        }
 
        // Store the count of N digit numbers
        // whose sum is divisible by K
        int res = 0;
 
        // Check if the number does not contain
        // any leading 0.
        int start = st == 1 ? 0 : 1;
 
        // Recurrence relation
        for (int i = start; i <= 9; i++) {
            res += countNum(N - 1, (sum + i) % K,
                            K, ((st | i) > 0) ? 1 : 0, dp);
        }
        return dp[N][sum][st] = res;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int N = 2, K = 7;
 
        // Stores the values of
        // overlapping subproblems
        int[][][] dp = new int[M][M][2];
 
        for (int[][] i : dp)
            for (int[] j : i)
                Arrays.fill(j, -1);
 
        System.out.print(countNum(N, 0, K, 0, dp));
    }
}
 
// This code is contributed by offbeat

Python3




# Python3 program to implement
# the above approach
 
# Function to count the N digit
# numbers whose sum is divisible by K
def countNum(N, sum, K, st, dp):
     
    # Base case
    if (N == 0 and sum == 0):
        return 1
 
    if (N < 0):
        return 0
 
    # If already computed
    # subproblem occurred
    if (dp[N][sum][st] != -1):
        return dp[N][sum][st]
 
    # Store the count of N digit
    # numbers whose sum is divisible by K
    res = 0
    start = 1
     
    # Check if the number does not contain
    # any leading 0.
    if (st == 1):
        start = 0
    else:
        start = 1
 
    # Recurrence relation
    for i in range(start, 10):
        min = 0
         
        if ((st | i) > 0):
            min = 1
        else:
            min = 0
             
        res += countNum(N - 1, (sum + i) % K,
                        K, min, dp)
        dp[N][sum][st] = res
         
    return dp[N][sum][st]
 
# Driver code
if __name__ == '__main__':
     
    N = 2
    K = 7
    M = 100
     
    # Stores the values of
    # overlapping subproblems
    dp = [[[-1 for i in range(2)]
               for j in range(M)]
               for j in range(M)]
 
    print(countNum(N, 0, K, 0, dp))
 
# This code is contributed by shikhasingrajput

C#




// C# program to implement
// the above approach
using System;
 
class GFG{
     
static int M = 1000;
 
// Function to count the N digit numbers
// whose sum is divisible by K
static int countNum(int N, int sum, int K,
                    int st, int[,, ] dp)
{
     
    // Base case
    if (N == 0 && sum == 0)
    {
        return 1;
    }
    if (N < 0)
    {
        return 0;
    }
 
    // If already computed
    // subproblem occurred
    if (dp[N, sum, st] != -1)
    {
        return dp[N, sum, st];
    }
 
    // Store the count of N digit numbers
    // whose sum is divisible by K
    int res = 0;
 
    // Check if the number does not contain
    // any leading 0.
    int start = (st == 1 ? 0 : 1);
     
    // Recurrence relation
    for(int i = start; i <= 9; i++)
    {
        res += countNum(N - 1, (sum + i) % K,
                        K, ((st | i) > 0) ? 1 : 0, dp);
    }
    return dp[N, sum, st] = res;
}
 
// Driver code
static public void Main()
{
    int N = 2, K = 7;
     
    // Stores the values of
    // overlapping subproblems
    int[,, ] dp = new int[M, M, 2];
 
    for(int i = 0; i < M; i++)
        for(int j = 0; j < M; j++)
            for(int k = 0; k < 2; k++)
                dp[i, j, k] = -1;
 
    Console.WriteLine(countNum(N, 0, K, 0, dp));
}
}
 
// This code is contributed by offbeat

Javascript




<script>
 
// JavaScript Program to implement
// the above approach
 
var M = 1000;
 
// Function to count the N digit numbers
// whose sum is divisible by K
function countNum(N, sum, K, st, dp)
{
    // Base case
    if (N == 0 && sum == 0) {
        return 1;
    }
    if (N < 0) {
        return 0;
    }
 
    // If already computed
    // subproblem occurred
    if (dp[N][sum][st] != -1) {
        return dp[N][sum][st];
    }
 
    // Store the count of N digit numbers
    // whose sum is divisible by K
    var res = 0;
 
    // Check if the number does not contain
    // any leading 0.
    var start = st == 1 ? 0 : 1;
 
    // Recurrence relation
    for (var i = start; i <= 9; i++) {
        res += countNum(N - 1, (sum + i) % K,
                        K, (st | i > 0), dp);
    }
 
    return dp[N][sum][st] = res;
}
 
// Driver Code
 
var N = 2, K = 7;
 
// Stores the values of
// overlapping subproblems
var dp = Array.from(Array(M), ()=>Array(M));
for(var i =0; i<M; i++)
        for(var j =0; j<M; j++)
            dp[i][j] = new Array(2).fill(-1);
document.write( countNum(N, 0, K, 0, dp));
 
 
</script>

Output:

12

Time Complexity:O(10*N*K)

Auxiliary Space: O(N*K)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!