Count numbers from a given range whose product of digits is K

Given three positive integers L, R and K, the task is to count the numbers in the range [L, R] whose product of digits is equal to K
Examples:
Input: L = 1, R = 130, K = 14
Output: 3
Explanation:Â
Numbers in the range [1, 100] whose sum of digits is K(= 14) are:Â
27 => 2 * 7 = 14Â
72 => 7 * 2 = 14Â
127 => 1 * 2 * 7 = 14Â
Therefore, the required output is 3.Input: L = 20, R = 10000, K = 14
Output: 20
Naive Approach: The simplest approach to solve this problem is to iterate over all the numbers in the range [L, R] and for every number, check if its product of digits is equal to K or not. If found to be true, then increment the count. Finally, print the count obtained.
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the product// of digits of a numberint prodOfDigit(int N){    // Stores product of    // digits of N    int res = 1;Â
    while (N) {Â
        // Update res        res = res * (N % 10);Â
        // Update N        N /= 10;    }Â
    return res;}Â
// Function to count numbers in the range// [0, X] whose product of digit is Kint cntNumRange(int L, int R, int K){    // Stores count of numbers in the range    // [L, R] whose product of digit is K    int cnt = 0;Â
    // Iterate over the range [L, R]    for (int i = L; i <= R; i++) {Â
        // If product of digits of        // i equal to K        if (prodOfDigit(i) == K) {Â
            // Update cnt            cnt++;        }    }Â
    return cnt;}Â
// Driver Codeint main(){Â Â Â Â int L = 20, R = 10000, K = 14;Â Â Â Â cout << cntNumRange(L, R, K);} |
Java
// Java program to implement// the above approachimport java.util.*;Â
class GFG{Â
// Function to find the product// of digits of a numberstatic int prodOfDigit(int N){       // Stores product of    // digits of N    int res = 1;    while (N > 0)     {Â
        // Update res        res = res * (N % 10);Â
        // Update N        N /= 10;    }Â
    return res;}Â
// Function to count numbers in the range// [0, X] whose product of digit is Kstatic int cntNumRange(int L, int R, int K){       // Stores count of numbers in the range    // [L, R] whose product of digit is K    int cnt = 0;Â
    // Iterate over the range [L, R]    for (int i = L; i <= R; i++)     {Â
        // If product of digits of        // i equal to K        if (prodOfDigit(i) == K)         {Â
            // Update cnt            cnt++;        }    }    return cnt;}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â int L = 20, R = 10000, K = 14;Â Â Â Â System.out.print(cntNumRange(L, R, K));}}Â
// This code is contributed by Amit Katiyar |
Python3
# Python3 program to implement# the above approachÂ
# Function to find the product# of digits of a numberdef prodOfDigit(N):         # Stores product of    # digits of N    res = 1Â
    while (N):                 # Update res        res = res * (N % 10)Â
        # Update N        N //= 10Â
    return resÂ
# Function to count numbers in the range# [0, X] whose product of digit is Kdef cntNumRange(L, R, K):         # Stores count of numbers in the range    # [L, R] whose product of digit is K    cnt = 0Â
    # Iterate over the range [L, R]    for i in range(L, R + 1):                 # If product of digits of        # i equal to K        if (prodOfDigit(i) == K):Â
            # Update cnt            cnt += 1Â
    return cntÂ
# Driver Codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â L, R, K = 20, 10000, 14Â Â Â Â Â Â Â Â Â print(cntNumRange(L, R, K))Â
# This code is contributed by mohit kumar 29 |
C#
// C# program to implement// the above approachusing System;  class GFG{      // Function to find the product// of digits of a numberstatic int prodOfDigit(int N){         // Stores product of    // digits of N    int res = 1;         while (N > 0)     {                 // Update res        res = res * (N % 10);          // Update N        N /= 10;    }    return res;}  // Function to count numbers in the range// [0, X] whose product of digit is Kstatic int cntNumRange(int L, int R, int K){        // Stores count of numbers in the range    // [L, R] whose product of digit is K    int cnt = 0;      // Iterate over the range [L, R]    for(int i = L; i <= R; i++)     {          // If product of digits of        // i equal to K        if (prodOfDigit(i) == K)         {              // Update cnt            cnt++;        }    }    return cnt;}  // Driver Codestatic void Main(){    int L = 20, R = 10000, K = 14;         Console.WriteLine(cntNumRange(L, R, K));}}Â
// This code is contributed by code_hunt |
Javascript
<script>// Javascript program to implement// the above approachÂ
// Function to find the product// of digits of a numberfunction prodOfDigit(N){    // Stores product of    // digits of N    let res = 1;Â
    while (N) {Â
        // Update res        res = res * (N % 10);Â
        // Update N        N = Math.floor(N/10);    }Â
    return res;}Â
// Function to count numbers in the range// [0, X] whose product of digit is Kfunction cntNumRange(L, R, K){Â
    // Stores count of numbers in the range    // [L, R] whose product of digit is K    let cnt = 0;Â
    // Iterate over the range [L, R]    for (let i = L; i <= R; i++) {Â
        // If product of digits of        // i equal to K        if (prodOfDigit(i) == K)         {Â
            // Update cnt            cnt++;        }    }Â
    return cnt;}Â
// Driver Code    let L = 20, R = 10000, K = 14;    document.write(cntNumRange(L, R, K));Â
// This code is contributed by manoj.</script> |
20
Time Complexity: O(R – L + 1) * log10(R)Â
Auxiliary Space: O(1)
Efficient approach: To optimize the above approach, the idea is to use Digit DP. Following are the dynamic programming states of the Digit DP:Â
Dynamic programming states are:Â
prod: Represents sum of digits.Â
tight: Check if sum of digits exceed K or not.Â
end: Stores the maximum possible value of ith digit of a number.Â
st: Check if a number contains leading 0 or not.Â
Â
Following are the Recurrence Relation of the Dynamic programming states:Â
- If i == 0 and st == 0:
ÂcntNum(N, K, st, tight): Returns the count of numbers in the range [0, X] whose product of digits is K.
Â
- Otherwise,
ÂcntNum(N, K, st, tight): Returns the count of numbers in the range [0, X] whose product of digits is K.
Â
Follow the steps below to solve the problem:Â Â
- Initialize a 3D array dp[N][K][tight] to compute and store the values of all subproblems of the above recurrence relation.
- Finally, return the value of dp[N][sum][tight].
Below is the implementation of the above approach:Â
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std;#define M 100Â
// Function to count numbers in the range// [0, X] whose product of digit is Kint cntNum(string X, int i, int prod, int K,           int st, int tight, int dp[M][M][2][2]){    // If count of digits in a number    // greater than count of digits in X    if (i >= X.length() || prod > K) {Â
        // If product of digits of a        // number equal to K        return prod == K;    }Â
    // If overlapping subproblems    // already occurred    if (dp[prod][i][tight][st] != -1) {        return dp[prod][i][tight][st];    }Â
    // Stores count of numbers whose    // product of digits is K    int res = 0;Â
    // Check if the numbers    // exceeds K or not    int end = tight ? X[i] - '0' : 9;Â
    // Iterate over all possible    // value of i-th digits    for (int j = 0; j <= end; j++) {Â
        // if number contains leading 0        if (j == 0 && !st) {Â
            // Update res            res += cntNum(X, i + 1, prod, K,                          false, (tight & (j == end)), dp);        }Â
        else {Â
            // Update res            res += cntNum(X, i + 1, prod * j, K,                          true, (tight & (j == end)), dp);        }Â
        // Update res    }Â
    // Return res    return dp[prod][i][tight][st] = res;}Â
// Utility function to count the numbers in// the range [L, R] whose prod of digits is Kint UtilCntNumRange(int L, int R, int K){    // Stores numbers in the form    // of string    string str = to_string(R);Â
    // Stores overlapping subproblems    int dp[M][M][2][2];Â
    // Initialize dp[][][] to -1    memset(dp, -1, sizeof(dp));Â
    // Stores count of numbers in    // the range [0, R] whose    // product of digits is k    int cntR = cntNum(str, 0, 1, K,                      false, true, dp);Â
    // Update str    str = to_string(L - 1);Â
    // Initialize dp[][][] to -1    memset(dp, -1, sizeof(dp));Â
    // Stores count of numbers in    // the range [0, L - 1] whose    // product of digits is k    int cntL = cntNum(str, 0, 1, K,                      false, true, dp);Â
    return (cntR - cntL);}Â
// Driver Codeint main(){Â Â Â Â int L = 20, R = 10000, K = 14;Â Â Â Â cout << UtilCntNumRange(L, R, K);} |
Java
// Java program to implement// the above approachimport java.util.*;Â
class GFG{Â Â Â Â Â static final int M = 100;Â
// Function to count numbers in the range// [0, X] whose product of digit is Kstatic int cntNum(String X, int i, int prod, int K,                    int st, int tight, int [][][][]dp){         // If count of digits in a number    // greater than count of digits in X    if (i >= X.length() || prod > K)    {                 // If product of digits of a        // number equal to K        return prod == K ? 1 : 0;    }Â
    // If overlapping subproblems    // already occurred    if (dp[prod][i][tight][st] != -1)    {        return dp[prod][i][tight][st];    }Â
    // Stores count of numbers whose    // product of digits is K    int res = 0;Â
    // Check if the numbers    // exceeds K or not    int end = tight > 0 ? X.charAt(i) - '0' : 9;Â
    // Iterate over all possible    // value of i-th digits    for(int j = 0; j <= end; j++)     {                 // If number contains leading 0        if (j == 0 && st == 0)        {                         // Update res            res += cntNum(X, i + 1, prod, K, 0,                   (tight & ((j == end) ? 1 : 0)), dp);        }        else        {                         // Update res            res += cntNum(X, i + 1, prod * j, K, 1,                   (tight & ((j == end) ? 1 : 0)), dp);        }    }Â
    // Return res    return dp[prod][i][tight][st] = res;}Â
// Utility function to count the numbers in// the range [L, R] whose prod of digits is Kstatic int UtilCntNumRange(int L, int R, int K){         // Stores numbers in the form    // of String    String str = String.valueOf(R);Â
    // Stores overlapping subproblems    int [][][][]dp = new int[M][M][2][2];Â
    // Initialize dp[][][] to -1    for(int i = 0; i < M; i++)    {        for(int j = 0; j < M; j++)        {            for(int k = 0; k < 2; k++)                for(int l = 0; l < 2; l++)                    dp[i][j][k][l] = -1;        }    }Â
    // Stores count of numbers in    // the range [0, R] whose    // product of digits is k    int cntR = cntNum(str, 0, 1, K,                      0, 1, dp);Â
    // Update str    str = String.valueOf(L - 1);Â
    // Initialize dp[][][] to -1    for(int i = 0;i<M;i++)    {        for(int j = 0; j < M; j++)        {            for(int k = 0; k < 2; k++)                for(int l = 0; l < 2; l++)                    dp[i][j][k][l] = -1;        }    }Â
    // Stores count of numbers in    // the range [0, L - 1] whose    // product of digits is k    int cntL = cntNum(str, 0, 1, K,                      0, 1, dp);Â
    return (cntR - cntL);}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â int L = 20, R = 10000, K = 14;Â Â Â Â Â Â Â Â Â System.out.print(UtilCntNumRange(L, R, K));}}Â
// This code is contributed by shikhasingrajput |
Python3
# Python 3 program to implement# the above approachM = 100Â
# Function to count numbers in the range# [0, X] whose product of digit is Kdef cntNum(X, i, prod, K, st, tight, dp):    end = 0         # If count of digits in a number    # greater than count of digits in X    if (i >= len(X) or prod > K):               # If product of digits of a        # number equal to K        if(prod == K):          return 1        else:          return 0Â
    # If overlapping subproblems    # already occurred    if (dp[prod][i][tight][st] != -1):        return dp[prod][i][tight][st]Â
    # Stores count of numbers whose    # product of digits is K    res = 0Â
    # Check if the numbers    # exceeds K or not    if(tight != 0):        end = ord(X[i]) - ord('0')Â
    # Iterate over all possible    # value of i-th digits    for j in range(end + 1):               # if number contains leading 0        if (j == 0 and st == 0):            # Update res            res += cntNum(X, i + 1, prod, K, False, (tight & (j == end)), dp)Â
        else:            # Update res            res += cntNum(X, i + 1, prod * j, K, True, (tight & (j == end)), dp)        # Update resÂ
    # Return res    dp[prod][i][tight][st] = res    return resÂ
# Utility function to count the numbers in# the range [L, R] whose prod of digits is Kdef UtilCntNumRange(L, R, K):    global M         # Stores numbers in the form    # of string    str1 = str(R)Â
    # Stores overlapping subproblems    dp = [[[[-1 for i in range(2)] for j in range(2)] for k in range(M)] for l in range(M)]Â
    # Stores count of numbers in    # the range [0, R] whose    # product of digits is k    cntR = cntNum(str1, 0, 1, K, False, True, dp)Â
    # Update str    str1 = str(L - 1)    dp = [[[[-1 for i in range(2)] for j in range(2)] for k in range(M)] for l in range(M)]Â
    # Stores count of numbers in    cntR = 20         # the range [0, L - 1] whose    # product of digits is k    cntL = cntNum(str1, 0, 1, K, False, True, dp)    return (cntR - cntL)Â
# Driver Codeif __name__ == '__main__':Â Â Â Â L = 20Â Â Â Â R = 10000Â Â Â Â K = 14Â Â Â Â print(UtilCntNumRange(L, R, K))Â
    # This code is contributed by SURENDRA_GANGWAR. |
C#
// C# program to implement// the above approachusing System;class GFG{Â
  static readonly int M = 100;Â
  // Function to count numbers in the range  // [0, X] whose product of digit is K  static int cntNum(String X, int i, int prod, int K,                    int st, int tight, int [,,,]dp)  {Â
    // If count of digits in a number    // greater than count of digits in X    if (i >= X.Length || prod > K)    {Â
      // If product of digits of a      // number equal to K      return prod == K ? 1 : 0;    }Â
    // If overlapping subproblems    // already occurred    if (dp[prod, i, tight, st] != -1)    {      return dp[prod, i, tight, st];    }Â
    // Stores count of numbers whose    // product of digits is K    int res = 0;Â
    // Check if the numbers    // exceeds K or not    int end = tight > 0 ? X[i] - '0' : 9;Â
    // Iterate over all possible    // value of i-th digits    for(int j = 0; j <= end; j++)     {Â
      // If number contains leading 0      if (j == 0 && st == 0)      {Â
        // Update res        res += cntNum(X, i + 1, prod, K, 0,                       (tight & ((j == end) ? 1 : 0)), dp);      }      else      {Â
        // Update res        res += cntNum(X, i + 1, prod * j, K, 1,                       (tight & ((j == end) ? 1 : 0)), dp);      }    }Â
    // Return res    return dp[prod, i, tight, st] = res;  }Â
  // Utility function to count the numbers in  // the range [L, R] whose prod of digits is K  static int UtilCntNumRange(int L, int R, int K)  {Â
    // Stores numbers in the form    // of String    String str = String.Join("", R);Â
    // Stores overlapping subproblems    int [,,,]dp = new int[M, M, 2, 2];Â
    // Initialize [,]dp[] to -1    for(int i = 0; i < M; i++)    {      for(int j = 0; j < M; j++)      {        for(int k = 0; k < 2; k++)          for(int l = 0; l < 2; l++)            dp[i, j, k, l] = -1;      }    }Â
    // Stores count of numbers in    // the range [0, R] whose    // product of digits is k    int cntR = cntNum(str, 0, 1, K,                      0, 1, dp);Â
    // Update str    str = String.Join("", L - 1);Â
    // Initialize [,]dp[] to -1    for(int i = 0; i < M; i++)    {      for(int j = 0; j < M; j++)      {        for(int k = 0; k < 2; k++)          for(int l = 0; l < 2; l++)            dp[i, j, k, l] = -1;      }    }Â
    // Stores count of numbers in    // the range [0, L - 1] whose    // product of digits is k    int cntL = cntNum(str, 0, 1, K,                      0, 1, dp);Â
    return (cntR - cntL);  }Â
  // Driver Code  public static void Main(String[] args)  {    int L = 20, R = 10000, K = 14;Â
    Console.Write(UtilCntNumRange(L, R, K));  }}Â
Â
Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// Javascript program to implement// the above approachÂ
let M = 100;Â
// Function to count numbers in the range// [0, X] whose product of digit is Kfunction cntNum(X, i, prod, K, st, tight, dp){    // If count of digits in a number    // greater than count of digits in X    if (i >= X.length || prod > K)    {                  // If product of digits of a        // number equal to K        return prod == K ? 1 : 0;    }      // If overlapping subproblems    // already occurred    if (dp[prod][i][tight][st] != -1)    {        return dp[prod][i][tight][st];    }      // Stores count of numbers whose    // product of digits is K    let res = 0;      // Check if the numbers    // exceeds K or not    let end = tight > 0 ? X[i] - '0' : 9;      // Iterate over all possible    // value of i-th digits    for(let j = 0; j <= end; j++)    {                  // If number contains leading 0        if (j == 0 && st == 0)        {                          // Update res            res += cntNum(X, i + 1, prod, K, 0,                  (tight & ((j == end) ? 1 : 0)), dp);        }        else        {                          // Update res            res += cntNum(X, i + 1, prod * j, K, 1,                  (tight & ((j == end) ? 1 : 0)), dp);        }    }      // Return res    return dp[prod][i][tight][st] = res;}Â
// Utility function to count the numbers in// the range [L, R] whose prod of digits is Kfunction UtilCntNumRange(L,R,K){    // Stores numbers in the form    // of String    let str = (R).toString();      // Stores overlapping subproblems    let dp = new Array(M);           // Initialize dp[][][] to -1    for(let i = 0; i < M; i++)    {        dp[i]=new Array(M);        for(let j = 0; j < M; j++)        {            dp[i][j]=new Array(2);            for(let k = 0; k < 2; k++)            {                dp[i][j][k]=new Array(2);                for(let l = 0; l < 2; l++)                    dp[i][j][k][l] = -1;            }        }    }      // Stores count of numbers in    // the range [0, R] whose    // product of digits is k    let cntR = cntNum(str, 0, 1, K,                      0, 1, dp);      // Update str    str = (L - 1).toString();      // Initialize dp[][][] to -1    for(let i = 0;i<M;i++)    {        for(let j = 0; j < M; j++)        {            for(let k = 0; k < 2; k++)                for(let l = 0; l < 2; l++)                    dp[i][j][k][l] = -1;        }    }      // Stores count of numbers in    // the range [0, L - 1] whose    // product of digits is k    let cntL = cntNum(str, 0, 1, K,                      0, 1, dp);      return (cntR - cntL);}Â
// Driver Codelet L = 20, R = 10000, K = 14;Â Â Â Â Â Â document.write(UtilCntNumRange(L, R, K));Â
// This code is contributed by unknown2108</script> |
20
Time Complexity: O(K * log10(R) * 10 * 4)
Auxiliary Space: O(K * log10(R) * 4)
Approach#3: Using functools
This approach takes three inputs, L, R, and K, and returns the count of numbers between L and R inclusive whose product of digits is equal to K. It does so by iterating over all numbers between L and R inclusive and checking if the product of their digits is equal to K using the reduce function from the functools module.
Algorithm
1. Initialize a counter variable to 0.
2. Iterate over all numbers between L and R inclusive using the range function.
3. For each number, convert it to a string and then apply the reduce function to compute the product of its digits.
4. Check if the product of digits is equal to K. If it is, increment the counter variable.
5. Return the counter variable as the output.
C++
#include <iostream>#include <string>Â
using namespace std;Â
// Function to count numbers with a product of digits equal to Kint count_numbers(int L, int R, int K) {Â Â Â Â int count = 0;Â
    // Loop through numbers in the given range    for (int num = L; num <= R; num++) {        // Convert the number to a string and split its digits        string numStr = to_string(num);Â
        // Calculate the product of digits        int product = 1;        for (char digit : numStr) {            product *= (digit - '0');        }Â
        // Check if the product matches the given value K        if (product == K) {            count++; // Increment the count if the condition is met        }    }Â
    return count; // Return the count of numbers satisfying the condition}Â
int main() {Â Â Â Â // Example usage:Â Â Â Â cout << count_numbers(1, 130, 14) << endl;Â Â Â Â Â Â cout << count_numbers(20, 10000, 14) << endl;Â
    return 0;} |
Java
public class ProductOfDigitsCount {Â
    // Function to count numbers with a product of digits equal to K    public static int countNumbers(int L, int R, int K) {        int count = 0;Â
        // Loop through numbers in the given range        for (int num = L; num <= R; num++) {            // Convert the number to a string and split its digits            String numStr = String.valueOf(num);Â
            // Calculate the product of digits            int product = 1;            for (char digit : numStr.toCharArray()) {                product *= Character.getNumericValue(digit);            }Â
            // Check if the product matches the given value K            if (product == K) {                count++; // Increment the count if the condition is met            }        }Â
        return count; // Return the count of numbers satisfying the condition    }Â
    public static void main(String[] args) {        // Example usage:        System.out.println(countNumbers(1, 130, 14));        System.out.println(countNumbers(20, 10000, 14));    }} |
Python3
import functoolsÂ
def count_numbers(L, R, K):Â Â Â Â return sum(1 for num in range(L, R+1) if functools.reduce(lambda x, y: int(x)*int(y), str(num)) == K)Â
# Example usage:print(count_numbers(1, 130, 14))Â print(count_numbers(20, 10000, 14))Â |
C#
using System;Â
class Program {    // Function to count numbers with a product of digits    // equal to K    static int CountNumbers(int L, int R, int K)    {        int count = 0;Â
        // Loop through numbers in the given range        for (int num = L; num <= R; num++) {            // Convert the number to a string and split its            // digits            string numStr = num.ToString();Â
            // Calculate the product of digits            int product = 1;            foreach(char digit in numStr)            {                product *= (digit - '0');            }Â
            // Check if the product matches the given value            // K            if (product == K) {                count++; // Increment the count if the                         // condition is met            }        }Â
        return count; // Return the count of numbers                      // satisfying the condition    }Â
    static void Main(string[] args)    {        // Example usage:        Console.WriteLine(CountNumbers(1, 130, 14));        Console.WriteLine(CountNumbers(20, 10000, 14));    }} |
Javascript
// Function to count numbers with a product of digits equal to Kfunction count_numbers(L, R, K) {    let count = 0;    // Loop through numbers in the given range    for (let num = L; num <= R; num++) {        // Convert the number to a string and split its digits        const digits = num.toString().split('');Â
        // Calculate the product of digits using the reduce function        const product = digits.reduce((x, y) => parseInt(x) * parseInt(y), 1);Â
        // Check if the product matches the given value K        if (product === K) {            count++; // Increment the count if the condition is met        }    }Â
    return count; // Return the count of numbers satisfying the condition}Â
// Example usage:console.log(count_numbers(1, 130, 14));Â Â Â // Output: 6console.log(count_numbers(20, 10000, 14)); // Output: 112 |
3 20
Time Complexity: O((R-L)*d), where d is the number of digits in R. This is because the code iterates over all numbers between L and R inclusive, and for each number, it applies the reduce function to compute the product of its digits, which takes O(d) time.
Auxiliary Space: O(d), where d is the number of digits in R. This is because the reduce function creates a new list of digits for each number and stores it in memory while computing the product of digits. The sum function also creates a new generator object, but it doesn’t require any additional memory to store the result. Overall, the memory used by the code scales linearly with the number of digits in R.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



