Open In App

Number of ways to split N as sum of K numbers from the given range

Improve
Improve
Like Article
Like
Save
Share
Report

Given four positive integer N, K, L, and R, the task is to split N as sum of K numbers lying in the range [L, R].
Note: Since the number of ways can be very large. Output answer modulo 1000000007.
Examples: 

Input : N = 12, K = 3, L = 1, R = 5 
Output : 10 
{2, 5, 5} 
{3, 4, 5} 
{3, 5, 4} 
{4, 3, 5} 
{4, 4, 4} 
{4, 5, 3} 
{5, 2, 5} 
{5, 3, 4} 
{5, 4, 3} 
{5, 5, 2}

Input : N = 23, K = 4, L = 2, R = 10 
Output : 480 

Naive Approach 
We can solve the problem using recursion. At each step of recursion try to make a group of size L to R all 
There will be two arguments in the recursion which changes: 

  • pos – the group number
  • left – how much of N is left to be distributed

Below is the implementation of the above approach:

C++




// C++ implementation to count the
// number of ways to divide N in K
// groups such that each group
// has elements in range [L, R]
 
#include <bits/stdc++.h>
 
using namespace std;
 
const int mod = 1000000007;
 
// Function to count the number
// of ways to divide the number N
// in K groups such that each group
// has number of elements in range [L, R]
int calculate(int pos, int left,
              int k, int L, int R)
{
    // Base Case
    if (pos == k) {
        if (left == 0)
            return 1;
        else
            return 0;
    }
 
    // if N is divides completely
    // into less than k groups
    if (left == 0)
        return 0;
 
    int answer = 0;
 
    // put all possible values
    // greater equal to prev
    for (int i = L; i <= R; i++) {
        if (i > left)
            break;
        answer = (answer + calculate(pos + 1,
                                     left - i, k, L, R))
                 % mod;
    }
    return answer;
}
 
// Function to count the number of
// ways to divide the number N
int countWaystoDivide(int n, int k,
                      int L, int R)
{
    return calculate(0, n, k, L, R);
}
 
// Driver Code
int main()
{
    int N = 12;
    int K = 3;
    int L = 1;
    int R = 5;
 
    cout << countWaystoDivide(N, K, L, R);
    return 0;
}


Java




// Java implementation to count the
// number of ways to divide N in K
// groups such that each group
// has elements in range [L, R]
class GFG{
 
static int mod = 1000000007;
 
// Function to count the number
// of ways to divide the number N
// in K groups such that each group
// has number of elements in range [L, R]
static int calculate(int pos, int left,
                     int k, int L, int R)
{
    // Base Case
    if (pos == k)
    {
        if (left == 0)
            return 1;
        else
            return 0;
    }
 
    // If N is divides completely
    // into less than k groups
    if (left == 0)
        return 0;
 
    int answer = 0;
 
    // Put all possible values
    // greater equal to prev
    for(int i = L; i <= R; i++)
    {
       if (i > left)
           break;
       answer = ((answer +
                  calculate(pos + 1,left - i,
                            k, L, R)) % mod);
    }
    return answer;
}
 
// Function to count the number of
// ways to divide the number N
static int countWaystoDivide(int n, int k,
                             int L, int R)
{
    return calculate(0, n, k, L, R);
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 12;
    int K = 3;
    int L = 1;
    int R = 5;
 
    System.out.print(countWaystoDivide(N, K, L, R));
}
}
 
// This code is contributed by Amit Katiyar


Python3




# Python3 implementation to count the
# number of ways to divide N in K
# groups such that each group
# has elements in range [L, R]
 
mod = 1000000007
 
# Function to count the number
# of ways to divide the number N
# in K groups such that each group
# has number of elements in range [L, R]
def calculate(pos, left, k, L, R):
     
    # Base Case
    if (pos == k):
        if (left == 0):
            return 1
        else:
            return 0
 
    # If N is divides completely
    # into less than k groups
    if (left == 0):
        return 0
         
    answer = 0
 
    # Put all possible values
    # greater equal to prev
    for i in range(L, R + 1):
        if (i > left):
            break
        answer = (answer +
                  calculate(pos + 1,
                            left - i, k, L, R)) % mod
    return answer
 
# Function to count the number of
# ways to divide the number N
def countWaystoDivide(n, k, L, R):
    return calculate(0, n, k, L, R)
 
# Driver Code
N = 12
K = 3
L = 1
R = 5
 
print(countWaystoDivide(N, K, L, R))
     
# This code is contributed by divyamohan123


C#




// C# implementation to count the
// number of ways to divide N in K
// groups such that each group
// has elements in range [L, R]
using System;
 
class GFG{
 
static int mod = 1000000007;
 
// Function to count the number
// of ways to divide the number N
// in K groups such that each group
// has number of elements in range [L, R]
static int calculate(int pos, int left,
                     int k, int L, int R)
{
     
    // Base Case
    if (pos == k)
    {
        if (left == 0)
            return 1;
        else
            return 0;
    }
 
    // If N is divides completely
    // into less than k groups
    if (left == 0)
        return 0;
 
    int answer = 0;
 
    // Put all possible values
    // greater equal to prev
    for(int i = L; i <= R; i++)
    {
       if (i > left)
           break;
       answer = ((answer +
                  calculate(pos + 1,left - i,
                            k, L, R)) % mod);
    }
    return answer;
}
 
// Function to count the number of
// ways to divide the number N
static int countWaystoDivide(int n, int k,
                             int L, int R)
{
    return calculate(0, n, k, L, R);
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 12;
    int K = 3;
    int L = 1;
    int R = 5;
 
    Console.Write(countWaystoDivide(N, K, L, R));
}
}
 
// This code is contributed by Amit Katiyar


Javascript




<script>
 
// Javascript implementation to count the
// number of ways to divide N in K
// groups such that each group
// has elements in range [L, R]
 
var mod = 1000000007;
 
// Function to count the number
// of ways to divide the number N
// in K groups such that each group
// has number of elements in range [L, R]
function calculate(pos, left, k, L, R)
{
    // Base Case
    if (pos == k) {
        if (left == 0)
            return 1;
        else
            return 0;
    }
 
    // if N is divides completely
    // into less than k groups
    if (left == 0)
        return 0;
 
    var answer = 0;
 
    // put all possible values
    // greater equal to prev
    for (var i = L; i <= R; i++) {
        if (i > left)
            break;
        answer = (answer + calculate(pos + 1,
                                     left - i, k, L, R))
                 % mod;
    }
    return answer;
}
 
// Function to count the number of
// ways to divide the number N
function countWaystoDivide(n, k, L, R)
{
    return calculate(0, n, k, L, R);
}
 
// Driver Code
var N = 12;
var K = 3;
var L = 1;
var R = 5;
document.write( countWaystoDivide(N, K, L, R));
 
// This code is contributed by noob2000.
</script>


Output: 

10

 

Time Complexity: O(NK).

Efficient Approach: In the previous approach we can see that we are solving the subproblems repeatedly, i.e. it follows the property of Overlapping Subproblems. So we can memoize the same using DP table. 

Below is the implementation of the above approach:

C++




// C++ implementation to count the
// number of ways to divide N in K
// groups such that each group
// has elements in range [L, R]
 
#include <bits/stdc++.h>
 
using namespace std;
 
const int mod = 1000000007;
 
// DP Table
int dp[1000][1000];
 
// Function to count the number
// of ways to divide the number N
// in K groups such that each group
// has number of elements in range [L, R]
int calculate(int pos, int left,
              int k, int L, int R)
{
    // Base Case
    if (pos == k) {
        if (left == 0)
            return 1;
        else
            return 0;
    }
 
    // if N is divides completely
    // into less than k groups
    if (left == 0)
        return 0;
 
    // If the subproblem has been
    // solved, use the value
    if (dp[pos][left] != -1)
        return dp[pos][left];
 
    int answer = 0;
 
    // put all possible values
    // greater equal to prev
    for (int i = L; i <= R; i++) {
        if (i > left)
            break;
        answer = (answer + calculate(pos + 1,
                                     left - i, k, L, R))
                 % mod;
    }
    return dp[pos][left] = answer;
}
 
// Function to count the number of
// ways to divide the number N
int countWaystoDivide(int n, int k,
                      int L, int R)
{
    // Initialize DP Table as -1
    memset(dp, -1, sizeof(dp));
    return calculate(0, n, k, L, R);
}
 
// Driver Code
int main()
{
    int N = 12;
    int K = 3;
    int L = 1;
    int R = 5;
 
    cout << countWaystoDivide(N, K, L, R);
    return 0;
}


Java




// Java implementation to count the
// number of ways to divide N in K
// groups such that each group
// has elements in range [L, R]
class GFG{
 
static int mod = 1000000007;
 
// DP Table
static int [][]dp = new int[1000][1000];
 
// Function to count the number
// of ways to divide the number N
// in K groups such that each group
// has number of elements in range [L, R]
static int calculate(int pos, int left,
                     int k, int L, int R)
{
     
    // Base Case
    if (pos == k)
    {
        if (left == 0)
            return 1;
        else
            return 0;
    }
 
    // If N is divides completely
    // into less than k groups
    if (left == 0)
        return 0;
 
    // If the subproblem has been
    // solved, use the value
    if (dp[pos][left] != -1)
        return dp[pos][left];
 
    int answer = 0;
 
    // Put all possible values
    // greater equal to prev
    for(int i = L; i <= R; i++)
    {
       if (i > left)
           break;
       answer = (answer + calculate(pos + 1, left - i,
                                      k, L, R)) % mod;
    }
    return dp[pos][left] = answer;
}
 
// Function to count the number of
// ways to divide the number N
static int countWaystoDivide(int n, int k,
                             int L, int R)
{
     
    // Initialize DP Table as -1
    for(int i = 0; i < 1000; i++)
    {
       for(int j = 0; j < 1000; j++)
       {
          dp[i][j] = -1;
       }
    }
    return calculate(0, n, k, L, R);
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 12;
    int K = 3;
    int L = 1;
    int R = 5;
 
    System.out.print(countWaystoDivide(N, K, L, R));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 implementation to count the
# number of ways to divide N in K
# groups such that each group
# has elements in range [L, R]
mod = 1000000007
  
# DP Table
dp = [[-1 for j in range(1000)]
          for i in range(1000)]
  
# Function to count the number
# of ways to divide the number N
# in K groups such that each group
# has number of elements in range [L, R]
def calculate(pos, left, k, L, R):
 
    # Base Case
    if (pos == k):
        if (left == 0):
            return 1
        else:
            return 0
 
    # if N is divides completely
    # into less than k groups
    if (left == 0):
        return 0
  
    # If the subproblem has been
    # solved, use the value
    if (dp[pos][left] != -1):
        return dp[pos][left]
  
    answer = 0
  
    # put all possible values
    # greater equal to prev
    for i in range(L, R + 1):
        if (i > left):
            break
         
        answer = (answer +
                  calculate(pos + 1,
                           left - i,
                           k, L, R)) % mod
     
    dp[pos][left] = answer
     
    return answer
 
# Function to count the number of
# ways to divide the number N
def countWaystoDivide(n, k, L, R):
     
    return calculate(0, n, k, L, R)
 
# Driver code
if __name__=="__main__":
     
    N = 12
    K = 3
    L = 1
    R = 5
  
    print(countWaystoDivide(N, K, L, R))
     
# This code is contributed by rutvik_56


C#




// C# implementation to count the
// number of ways to divide N in K
// groups such that each group
// has elements in range [L, R]
using System;
class GFG{
 
static int mod = 1000000007;
 
// DP Table
static int [,]dp = new int[1000, 1000];
 
// Function to count the number
// of ways to divide the number N
// in K groups such that each group
// has number of elements in range [L, R]
static int calculate(int pos, int left,
                     int k, int L, int R)
{
     
    // Base Case
    if (pos == k)
    {
        if (left == 0)
            return 1;
        else
            return 0;
    }
 
    // If N is divides completely
    // into less than k groups
    if (left == 0)
        return 0;
 
    // If the subproblem has been
    // solved, use the value
    if (dp[pos, left] != -1)
        return dp[pos, left];
 
    int answer = 0;
 
    // Put all possible values
    // greater equal to prev
    for(int i = L; i <= R; i++)
    {
        if (i > left)
            break;
        answer = (answer + calculate(pos + 1, left - i,
                                       k, L, R)) % mod;
    }
    return dp[pos, left] = answer;
}
 
// Function to count the number of
// ways to divide the number N
static int countWaystoDivide(int n, int k,
                             int L, int R)
{
     
    // Initialize DP Table as -1
    for(int i = 0; i < 1000; i++)
    {
        for(int j = 0; j < 1000; j++)
        {
            dp[i, j] = -1;
        }
    }
    return calculate(0, n, k, L, R);
}
 
// Driver Code
public static void Main()
{
    int N = 12;
    int K = 3;
    int L = 1;
    int R = 5;
 
    Console.Write(countWaystoDivide(N, K, L, R));
}
}
 
// This code is contributed by Code_Mech


Javascript




<script>
 
// JavaScript implementation to count the
// number of ways to divide N in K
// groups such that each group
// has elements in range [L, R]
 
var mod = 1000000007;
 
// DP Table
var dp = Array.from(Array(1000), ()=>Array(1000));
 
// Function to count the number
// of ways to divide the number N
// in K groups such that each group
// has number of elements in range [L, R]
function calculate(pos, left, k, L, R)
{
    // Base Case
    if (pos == k) {
        if (left == 0)
            return 1;
        else
            return 0;
    }
 
    // if N is divides completely
    // into less than k groups
    if (left == 0)
        return 0;
 
    // If the subproblem has been
    // solved, use the value
    if (dp[pos][left] != -1)
        return dp[pos][left];
 
    var answer = 0;
 
    // put all possible values
    // greater equal to prev
    for (var i = L; i <= R; i++) {
        if (i > left)
            break;
        answer = (answer + calculate(pos + 1,
                                     left - i, k, L, R))
                 % mod;
    }
    return dp[pos][left] = answer;
}
 
// Function to count the number of
// ways to divide the number N
function countWaystoDivide(n, k, L, R)
{
    // Initialize DP Table as -1
    dp = Array.from(Array(1000), ()=>Array(1000).fill(-1));
    return calculate(0, n, k, L, R);
}
 
// Driver Code
var N = 12;
var K = 3;
var L = 1;
var R = 5;
document.write( countWaystoDivide(N, K, L, R));
 
 
</script>


Output: 

10

 

Time Complexity: O(N*K).
Auxiliary Space: O(N*K).
 

Efficient approach : Using DP Tabulation method ( Iterative approach )

The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memorization(top-down) because memorization method needs extra stack space of recursion calls.

Steps to solve this problem :

  • Create a vector to store the solution of the subproblems.
  • Initialize the table with base cases
  • Fill up the table iteratively
  • Return the final solution

Implementation :

C++




#include <bits/stdc++.h>
 
using namespace std;
 
const int mod = 1000000007;
 
int dp[1000][1000];
 
// Function to count the number
// of ways to divide the number N
// in K groups such that each group
int countWaystoDivide(int n, int k, int L, int R) {
    memset(dp, 0, sizeof(dp));
          
      // Base Case
    dp[0][0] = 1;
   
      // Loop to traverse the matrix and compute the subproblems
    for (int i = 1; i <= k; i++) {
        for (int j = 0; j <= n; j++) {
            for (int l = L; l <= R; l++) {
                if (l > j) break;
                   
                  // update Dp with its previous computations
                dp[i][j] = (dp[i][j] + dp[i - 1][j - l]) % mod;
            }
        }
    }
   
      //return answer stored at last index
    return dp[k][n];
}
 
// Driver Code
int main() {
    int N = 12;
    int K = 3;
    int L = 1;
    int R = 5;
     
      // function call
    cout << countWaystoDivide(N, K, L, R);
    return 0;
}


Java




//GFG
//Java code for the given approach
 
import java.util.*;
 
public class Main {
    static final int MOD = 1000000007;
 
    public static int countWaystoDivide(int n, int k, int L, int R) {
        int[][] dp = new int[k+1][n+1];
 
        // Base Case
        dp[0][0] = 1;
 
        // Loop to traverse the matrix and compute the subproblems
        for (int i = 1; i <= k; i++) {
            for (int j = 0; j <= n; j++) {
                for (int l = L; l <= R; l++) {
                    if (l > j) break;
 
                    // update Dp with its previous computations
                    dp[i][j] = (dp[i][j] + dp[i - 1][j - l]) % MOD;
                }
            }
        }
 
        //return answer stored at last index
        return dp[k][n];
    }
 
    public static void main(String[] args) {
        int N = 12;
        int K = 3;
        int L = 1;
        int R = 5;
 
        // function call
        System.out.println(countWaystoDivide(N, K, L, R));
    }
}
 
//This code is written Sundaram


Python3




mod = 1000000007
dp = []
 
# Function to count the number
# of ways to divide the number N
# in K groups such that each group
def countWaystoDivide(n, k, L, R):
    for i in range(k + 1):
        dp.append([0] * (n + 1))
 
    # Base Case
    dp[0][0] = 1
 
    # Loop to traverse the matrix and compute the subproblems
    for i in range(1, k + 1):
        for j in range(n + 1):
            for l in range(L, R + 1):
                if l > j:
                    break
 
                # update Dp with its previous computations
                dp[i][j] = (dp[i][j] + dp[i - 1][j - l]) % mod
 
    #return answer stored at last index
    return dp[k][n]
 
# Driver Code
N = 12
K = 3
L = 1
R = 5
 
# function call
print(countWaystoDivide(N, K, L, R))


C#




using System;
 
public class GFG {
  const int mod = 1000000007;
  static int[, ] dp = new int[1000, 1000];
 
  // Function to count the number
  // of ways to divide the number N
  // in K groups such that each group
  static int countWaystoDivide(int n, int k, int L, int R)
  {
    Array.Clear(dp, 0, dp.Length);
 
    // Base Case
    dp[0, 0] = 1;
 
    // Loop to traverse the matrix and compute the
    // subproblems
    for (int i = 1; i <= k; i++) {
      for (int j = 0; j <= n; j++) {
        for (int l = L; l <= R; l++) {
          if (l > j)
            break;
 
          // update Dp with its previous
          // computations
          dp[i, j] = (dp[i, j] + dp[i - 1, j - l])
            % mod;
        }
      }
    }
 
    // return answer stored at last index
    return dp[k, n];
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 12;
    int K = 3;
    int L = 1;
    int R = 5;
 
    // function call
    Console.WriteLine(countWaystoDivide(N, K, L, R));
  }
}
 
// This code is contributed by user_dtewbxkn77n


Javascript




const mod = 1000000007;
const dp = [];
 
// Function to count the number
// of ways to divide the number N
// in K groups such that each group
function countWaystoDivide(n, k, L, R) {
  for (let i = 0; i <= k; i++) {
    dp[i] = [];
    for (let j = 0; j <= n; j++) {
      dp[i][j] = 0;
    }
  }
 
  // Base Case
  dp[0][0] = 1;
 
  // Loop to traverse the matrix and compute the subproblems
  for (let i = 1; i <= k; i++) {
    for (let j = 0; j <= n; j++) {
      for (let l = L; l <= R; l++) {
        if (l > j) break;
 
        // update Dp with its previous computations
        dp[i][j] = (dp[i][j] + dp[i - 1][j - l]) % mod;
      }
    }
  }
 
  //return answer stored at last index
  return dp[k][n];
}
 
// Driver Code
const N = 12;
const K = 3;
const L = 1;
const R = 5;
 
// function call
console.log(countWaystoDivide(N, K, L, R));


Output

10

Time Complexity: O(N*K).
Auxiliary Space: O(N*K).



Last Updated : 19 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads