Open In App

Count of integers from the range [0, N] whose digit sum is a multiple of K

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integers n and k, the task is to calculate the number of integers in the range [0, n] whose digit sum is a multiple of k.

Examples:  

Input: n = 10, k = 5 
Output:
Explanation: 0 and 5 are the only possible integers.

Input: n = 30, k = 4 
Output: 7  

Using Brute Force Method - O(n) Time and O(1) Space

The idea is to loop through the range [0, n] and check if the sum of the digits of the numbers are multiples of k or not.

C++
// C++ program to count of integers
// from the range [0, N] whose digit
// sum is a multiple of K
#include <bits/stdc++.h>
using namespace std;

// Function to count numbers having
// k consecutive set bits
int count(int n, int k) {
    int ans = 0;

    for (int i = 0; i <= n; i++) {
        int num = i;

        // Variable to count digit sum
        int sum = 0;

        while (num > 0) {
            sum += (num % 10);
            num = num / 10;
        }

        // Check if digit sum if multiple
        // of k.
        if (sum % k == 0)
            ans++;
    }

    return ans;
}

int main() {
  
    int n = 10, k = 5;
    cout << count(n, k) << endl;

    return 0;
}
Java
// Java program to count of integers 
// from the range [0, N] whose digit
// sum is a multiple of K

class GfG {

    static int count(int n, int k) {
        int ans = 0;

        for (int i = 0; i <= n; i++) {
            int num = i;

            // Variable to count digit sum
            int sum = 0;

            while (num > 0) {
                sum += (num % 10);
                num = num / 10;
            }

            // Check if digit sum if multiple
            // of k.
            if (sum % k == 0) ans++;
        }

        return ans;
    }

    public static void main(String[] args) {
        int n = 10, k = 5;
        System.out.println(count(n, k));
    }
}
Python
# Python program to count of integers 
# from the range [0, N] whose digit
# sum is a multiple of K

def count(n, k):
    ans = 0

    for i in range(n + 1):
        num = i

        # Variable to count digit sum
        sum = 0

        while num > 0:
            sum += (num % 10)
            num //= 10

        # Check if digit sum if multiple
        # of k.
        if sum % k == 0:
            ans += 1

    return ans

if __name__ == "__main__":
    n, k = 10, 5
    print(count(n, k))
C#
// C# program to count of integers 
// from the range [0, N] whose digit
// sum is a multiple of K

using System;

class GfG {

    static int count(int n, int k) {
        int ans = 0;

        for (int i = 0; i <= n; i++) {
            int num = i;

            // Variable to count digit sum
            int sum = 0;

            while (num > 0) {
                sum += (num % 10);
                num /= 10;
            }

            // Check if digit sum if multiple
            // of k.
            if (sum % k == 0) ans++;
        }

        return ans;
    }

    static void Main(string[] args) {
        int n = 10, k = 5;
        Console.WriteLine(count(n, k));
    }
}
JavaScript
// JavaScript program to count of integers 
// from the range [0, N] whose digit
// sum is a multiple of K

function count(n, k) {
    let ans = 0;

    for (let i = 0; i <= n; i++) {
        let num = i;

        // Variable to count digit sum
        let sum = 0;

        while (num > 0) {
            sum += (num % 10);
            num = Math.floor(num / 10);
        }

        // Check if digit sum if multiple
        // of k.
        if (sum % k === 0) ans++;
    }

    return ans;
}

let n = 10, k = 5;
console.log(count(n, k));

Output
2

 Using Dynamic Programming - O(k*len(n)) Time and O(k*len(n)) Space

The idea is to use a digit dynamic programming (Digit DP) approach to solve the problem, where we recursively construct numbers from the most significant digit (MSD) to the least significant digit (LSD). The aim is to count numbers in the range [0, n] whose digit sum is divisible by k.

At each step, we analyze the current digit and make decisions while keeping track of information about the sum and constraints.

The DP state is represented by the following:

  • i: The current position of the digit being processed (starting from 0).
  • sum: The current sum of the digits modulo k.
  • tight: A boolean indicating whether the number being formed is still constrained by n.

Base Case:

If all digits are processed (i == num.length()), return 1 if sum == 0 (i.e., the sum is divisible by k); otherwise, return 0.

Step by step explanation:

  • Recursively process each digit of the number n starting from the most significant digit.
  • At each position, determine the possible digits (0 to 9) that can be placed based on whether the number being constructed is still constrained by n.
  • Maintain the sum of the digits modulo k (using sum % k) to ensure efficient state representation. This reduces the possible values for the sum to [0, k-1], avoiding unnecessary computation.
C++
// C++ program to count of integers
// from the range [0, N] whose digit
// sum is a multiple of K
#include <bits/stdc++.h>
using namespace std;

int countRecur(int i, int sum, int tight, string &num, 
               int k, vector<vector<vector<int>>> &memo) {
    if (i == num.length()) {
        return sum == 0 ? 1 : 0;
    }

    // If value is memoized, return it.
    if (memo[i][sum][tight] != -1) {
        return memo[i][sum][tight];
    }

    int digit = num[i] - '0';
    int ans = 0;

    //  Determine upper limit
    int limit = tight ? digit : 9;

    for (int j = 0; j <= limit; j++) {
        ans += countRecur(i + 1, (sum + j) % k,
		tight && (j == digit), num, k, memo);
    }

    return memo[i][sum][tight] = ans;
}

// Function to count numbers having
// k consecutive set bits
int count(int n, int k) {
  
    string num = to_string(n);
    vector<vector<vector<int>>> memo(num.length(), 
	vector<vector<int>>(k, vector<int>(2, -1)));

    return countRecur(0, 0, true, num, k, memo);
}

int main() {
  
    int n = 10, k = 5;
    cout << count(n, k) << endl;

    return 0;
}
Java
// Java program to count of integers 
// from the range [0, N] whose digit
// sum is a multiple of K

class GfG {

    static int countRecur(int i, int sum, int tight, 
    String num, int k, int[][][] memo) {
        if (i == num.length()) {
            return sum == 0 ? 1 : 0;
        }

        // If value is memoized, return it.
        if (memo[i][sum][tight] != -1) {
            return memo[i][sum][tight];
        }

        int digit = num.charAt(i) - '0';
        int ans = 0;

        // Determine upper limit
        int limit = tight == 1 ? digit : 9;

        for (int j = 0; j <= limit; j++) {
            ans += countRecur(i + 1, (sum + j) % k, 
            tight == 1 && j == digit ? 1 : 0, num, k, memo);
        }

        return memo[i][sum][tight] = ans;
    }

    static int count(int n, int k) {
        String num = Integer.toString(n);
        int[][][] memo = new int[num.length()][k][2];
        for (int[][] arr2D : memo) {
            for (int[] arr1D : arr2D) {
                java.util.Arrays.fill(arr1D, -1);
            }
        }
        return countRecur(0, 0, 1, num, k, memo);
    }

    public static void main(String[] args) {
        int n = 10, k = 5;
        System.out.println(count(n, k));
    }
}
Python
# Python program to count of integers 
# from the range [0, N] whose digit
# sum is a multiple of K

def countRecur(i, sum, tight, num, k, memo):
    if i == len(num):
        return 1 if sum == 0 else 0

    # If value is memoized, return it.
    if memo[i][sum][tight] != -1:
        return memo[i][sum][tight]

    digit = int(num[i])
    ans = 0

    # Determine upper limit
    limit = digit if tight else 9

    for j in range(limit + 1):
        ans += countRecur(i + 1, (sum + j) % k, tight \
                          and (j == digit), num, k, memo)

    memo[i][sum][tight] = ans
    return ans

def count(n, k):
    num = str(n)
    memo = [[[-1 for _ in range(2)] for _ in range(k)] for _ in range(len(num))]
    return countRecur(0, 0, True, num, k, memo)

if __name__ == "__main__":
    n, k = 10, 5
    print(count(n, k))
C#
// C# program to count of integers 
// from the range [0, N] whose digit
// sum is a multiple of k

using System;

class GfG {

    static int countRecur(int i, int sum, int tight, 
    string num, int k, int[,,] memo) {
        if (i == num.Length) {
            return sum == 0 ? 1 : 0;
        }

        // If value is memoized, return it.
        if (memo[i, sum, tight] != -1) {
            return memo[i, sum, tight];
        }

        int digit = num[i] - '0';
        int ans = 0;

        // Determine upper limit
        int limit = tight == 1 ? digit : 9;

        for (int j = 0; j <= limit; j++) {
            ans += countRecur(i + 1, (sum + j) % k, 
            tight == 1 && j == digit ? 1 : 0, num, k, memo);
        }

        memo[i, sum, tight] = ans;
        return ans;
    }

    static int count(int n, int k) {
        string num = n.ToString();
        int[,,] memo = new int[num.Length, k, 2];
        for (int i = 0; i < num.Length; i++) {
            for (int j = 0; j < k; j++) {
                for (int l = 0; l < 2; l++) {
                    memo[i, j, l] = -1;
                }
            }
        }
        return countRecur(0, 0, 1, num, k, memo);
    }

    static void Main(string[] args) {
        int n = 10, k = 5;
        Console.WriteLine(count(n, k));
    }
}
JavaScript
// JavaScript program to count of integers 
// from the range [0, n] whose digit
// sum is a multiple of k

function countRecur(i, sum, tight, num, k, memo) {
    if (i === num.length) {
        return sum === 0 ? 1 : 0;
    }

    // If value is memoized, return it.
    if (memo[i][sum][tight] !== -1) {
        return memo[i][sum][tight];
    }

    let digit = parseInt(num[i], 10);
    let ans = 0;

    // Determine upper limit
    let limit = tight ? digit : 9;

    for (let j = 0; j <= limit; j++) {
        ans += countRecur(i + 1, (sum + j) % k, 
        (tight && j === digit)?1:0, num, k, memo);
    }

    memo[i][sum][tight] = ans;
    return ans;
}

function count(n, k) {
    let num = n.toString();
    let memo = Array.from({ length: num.length }, () =>
        Array.from({ length: k }, () => Array(2).fill(-1))
    );
    return countRecur(0, 0, 1, num, k, memo);
}

let n = 10, k = 5;
console.log(count(n, k));

Output
2

Practice Tags :

Similar Reads