The Wayback Machine - https://web.archive.org/web/20240602140618/https://www.geeksforgeeks.org/number-of-non-negative-integral-solutions-of-sum-equation/
Open In App

Number of non-negative integral solutions of sum equation

Last Updated : 29 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number n (number of variables) and val (sum of the variables), find out how many such non-negative integral solutions are possible. 

Examples : 

Input : n = 5, val = 1
Output : 5
Explanation:
x1 + x2 + x3 + x4 + x5 = 1
Number of possible solution are :
(0 0 0 0 1), (0 0 0 1 0), (0 0 1 0 0),
(0 1 0 0 0), (1 0 0 0 0)
Total number of possible solutions are 5
Input : n = 5, val = 4
Output : 70
Explanation:
x1 + x2 + x3 + x4 + x5 = 4
Number of possible solution are:
(1 1 1 1 0), (1 0 1 1 1), (0 1 1 1 1),
(2 1 0 0 1), (2 2 0 0 0)........ so on......
Total numbers of possible solutions are 70

Asked in: Microsoft Interview 

1. Make a recursive function call to countSolutions(int n, int val) 
2. Call this Solution function countSolutions(n-1, val-i) until n = 1 and val >=0 and then return 1.

Below is the implementation of above approach:

C++




// CPP program to find the numbers
// of non negative integral solutions
#include<iostream>
using namespace std;
 
// return number of non negative
// integral solutions
int countSolutions(int n, int val)
{
    // initialize total = 0
    int total = 0;
 
    // Base Case if n = 1 and val >= 0
    // then it should return 1
    if (n == 1 && val >=0)
        return 1;
 
    // iterate the loop till equal the val
    for (int i = 0; i <= val; i++){
         
        // total solution of equations
        // and again call the recursive
        // function Solutions(variable,value)
        total += countSolutions(n-1, val-i);
         
    }
     
    // return the total no possible solution
    return total;
}
 
// driver code
int main(){
     
    int n = 5;
    int val = 20;
     
    cout<<countSolutions(n, val);
}
 
//This code is contributed by Smitha Dinesh Semwal


Java




// Java program to find the numbers
// of non negative integral solutions
class GFG {
 
  // return number of non negative
  // integral solutions
  static int countSolutions(int n, int val) {
 
    // initialize total = 0
    int total = 0;
 
    // Base Case if n = 1 and val >= 0
    // then it should return 1
    if (n == 1 && val >= 0)
      return 1;
 
    // iterate the loop till equal the val
    for (int i = 0; i <= val; i++) {
 
      // total solution of equations
      // and again call the recursive
      // function Solutions(variable, value)
      total += countSolutions(n - 1, val - i);
    }
 
    // return the total no possible solution
    return total;
  }
 
  // Driver code
  public static void main(String[] args) {
    int n = 5;
    int val = 20;
 
    System.out.print(countSolutions(n, val));
  }
}
 
// This code is contributed by Anant Agarwal.


Python3




# Python3 program to find the numbers
# of non negative integral solutions
 
# return number of non negative
# integral solutions
def countSolutions(n, val):
 
    # initialize total = 0
    total = 0
 
    # Base Case if n = 1 and val >= 0
    # then it should return 1
    if n == 1 and val >=0:
        return 1
 
    # iterate the loop till equal the val
    for i in range(val+1):
     
        # total solution of equations
        # and again call the recursive
        # function Solutions(variable,value)
        total += countSolutions(n-1, val-i)
 
    # return the total no possible solution
    return total
 
# driver code
n = 5
val = 20
print(countSolutions(n, val))


C#




// C# program to find the numbers
// of non negative integral solutions
using System;
 
class GFG {
 
    // return number of non negative
    // integral solutions
    static int countSolutions(int n, int val) {
     
        // initialize total = 0
        int total = 0;
     
        // Base Case if n = 1 and val >= 0
        // then it should return 1
        if (n == 1 && val >= 0)
        return 1;
     
        // iterate the loop till equal the val
        for (int i = 0; i <= val; i++) {
         
            // total solution of equations
            // and again call the recursive
            // function Solutions(variable, value)
            total += countSolutions(n - 1, val - i);
        }
     
        // return the total no possible solution
        return total;
    }
     
    // Driver code
    public static void Main()
    {
        int n = 5;
        int val = 20;
     
        Console.WriteLine(countSolutions(n, val));
    }
}
 
// This code is contributed by Anant vt_m.


Javascript




<script>
 
// JavaScript program to find the numbers
// of non negative integral solutions
 
  // return number of non negative
  // integral solutions
  function countSolutions(n, val) {
   
    // initialize total = 0
    let total = 0;
   
    // Base Case if n = 1 and val >= 0
    // then it should return 1
    if (n == 1 && val >= 0)
      return 1;
   
    // iterate the loop till equal the val
    for (let i = 0; i <= val; i++) {
   
      // total solution of equations
      // and again call the recursive
      // function Solutions(variable, value)
      total += countSolutions(n - 1, val - i);
    }
   
    // return the total no possible solution
    return total;
  }
 
// Driver code
         
        let n = 5;
        let val = 20;
   
    document.write(countSolutions(n, val));
         
</script>


PHP




<?php
// PHP program to find the numbers
// of non negative integral solutions
 
// return number of non negative
// integral solutions
function countSolutions($n, $val)
{
    // initialize total = 0
    $total = 0;
 
    // Base Case if n = 1 and
    // val >= 0 then it should
    // return 1
    if ($n == 1 && $val >=0)
        return 1;
 
    // iterate the loop
    // till equal the val
    for ($i = 0; $i <= $val; $i++)
    {
         
        // total solution of equations
        // and again call the recursive
        // function Solutions(variable,value)
        $total += countSolutions($n - 1,
                                 $val - $i);
         
    }
     
    // return the total
    // no possible solution
    return $total;
}
 
// Driver Code
$n = 5;
$val = 20;
 
echo countSolutions($n, $val);
 
// This code is contributed by nitin mittal.
?>


Output : 

10626

Dynamic Programming Approach:

(Using Memoization)

C++




// CPP program to find the numbers
// of non negative integral solutions
#include<bits/stdc++.h>
using namespace std;
 
int dp[1001][1001];
 
// return number of non negative
// integral solutions
int countSolutions(int n, int val)
{
    // initialize total = 0
    int total = 0;
 
    // Base Case if n = 1 and val >= 0
    // then it should return 1
    if (n == 1 && val >=0) {
        return 1;
    }
   
    // If a value already present in dp,
    // return it
    if(dp[n][val] != -1) {
        return dp[n][val];
    }
     
    // iterate the loop till equal the val
    for (int i = 0; i <= val; i++){
         
        // total solution of equations
        // and again call the recursive
        // function Solutions(variable,value)
        total += countSolutions(n-1, val-i);
         
    }
     
    // Store the value in dp
    dp[n][val] = total;
     
    // Return dp
    return dp[n][val];
}
 
// driver code
int main(){
     
    int n = 5;
    int val = 20;
     
    memset(dp, -1, sizeof(dp));
     
    cout << countSolutions(n, val);
}


Java




// Java program to find the numbers
// of non negative integral solutions
import java.util.*;
public class GFG
{
  static int dp[][] = new int[1001][1001];
 
  // return number of non negative
  // integral solutions
  static int countSolutions(int n, int val)
  {
    // initialize total = 0
    int total = 0;
 
    // Base Case if n = 1 and val >= 0
    // then it should return 1
    if (n == 1 && val >=0) {
      return 1;
    }
 
    // If a value already present in dp,
    // return it
    if(dp[n][val] != -1) {
      return dp[n][val];
    }
 
    // iterate the loop till equal the val
    for (int i = 0; i <= val; i++){
 
      // total solution of equations
      // and again call the recursive
      // function Solutions(variable,value)
      total += countSolutions(n-1, val-i);
 
    }
 
    // Store the value in dp
    dp[n][val] = total;
 
    // Return dp
    return dp[n][val];
  }
 
  // driver code
  public static void main(String args[]){
 
    int n = 5;
    int val = 20;
 
    for(int i = 0; i < 1001; i++) {
      for(int j = 0; j < 1001; j++) {
        dp[i][j]=-1;
      }
    }
 
    System.out.println(countSolutions(n, val));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Python3




# Python3 program to find the numbers
# of non negative integral solutions
 
# Taking the matrix as globally
dp = [[-1 for i in range(1001)]
          for j in range(1001)]
 
# Return number of non negative
# integral solutions
def countSolutions(n, val):
 
    # Initialize total = 0
    total = 0
 
    # Base Case if n = 1 and val >= 0
    # then it should return 1
    if n == 1 and val >= 0:
        return 1
     
    # If a value is already present
    # in dp
    if (dp[n][val] != -1):
        return dp[n][val]
     
    # Iterate the loop till equal the val
    for i in range(val + 1):
     
        # total solution of equations
        # and again call the recursive
        # function Solutions(variable,value)
        total += countSolutions(n - 1, val - i)
 
    # Return the total no possible solution
    dp[n][val] = total
    return dp[n][val]
 
# Driver code
n = 5
val = 20
 
print(countSolutions(n, val))
 
# This code is contributed by Samim Hossain Mondal.


C#




// C# program to find the numbers
// of non negative integral solutions
using System;
class GFG
{
  static int [,]dp = new int[1001, 1001];
 
  // return number of non negative
  // integral solutions
  static int countSolutions(int n, int val)
  {
    // initialize total = 0
    int total = 0;
 
    // Base Case if n = 1 and val >= 0
    // then it should return 1
    if (n == 1 && val >=0) {
      return 1;
    }
 
    // If a value already present in dp,
    // return it
    if(dp[n, val] != -1) {
      return dp[n, val];
    }
 
    // iterate the loop till equal the val
    for (int i = 0; i <= val; i++){
 
      // total solution of equations
      // and again call the recursive
      // function Solutions(variable,value)
      total += countSolutions(n-1, val-i);
 
    }
 
    // Store the value in dp
    dp[n, val] = total;
 
    // Return dp
    return dp[n, val];
  }
 
  // driver code
  public static void Main(){
 
    int n = 5;
    int val = 20;
 
    for(int i = 0; i < 1001; i++) {
      for(int j = 0; j < 1001; j++) {
        dp[i, j] = -1;
      }
    }
 
    Console.Write(countSolutions(n, val));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
// JavaScript program to find the numbers
// of non negative integral solutions
  var dp = new Array(1001);
   
  // Loop to create 2D array using 1D array
  for (var i = 0; i < dp.length; i++) {
      dp[i] = new Array(1001);
  }
   
  // return number of non negative
  // integral solutions
  function countSolutions(n, val) {
   
    // initialize total = 0
    let total = 0;
   
    // Base Case if n = 1 and val >= 0
    // then it should return 1
    if (n == 1 && val >= 0)
      return 1;
     
    // if a value is already
    // present in dp
    if(dp[n][val] != -1)
        return dp[n][val];
     
    // iterate the loop till equal the val
    for (let i = 0; i <= val; i++) {
   
      // total solution of equations
      // and again call the recursive
      // function Solutions(variable, value)
      total += countSolutions(n - 1, val - i);
    }
   
    // return the total no possible solution
    return dp[n][val] = total;
  }
 
// Driver code
let n = 5;
let val = 20;
 
for(let i = 0; i < 1001; i++) {
    for(let j = 0; j < 1001; j++) {
        dp[i][j] = -1;
    }
}
document.write(countSolutions(n, val));
 
// This code is contributed by Samim Hossain Mondal.  
</script>


Output

10626







Time Complexity: O(n * val)

Auxiliary Space: O(n * val)

Dynamic Programming Approach: (Bottom-Up)

The approach used here is a bottom-up dynamic programming approach. We start with the simplest case (one variable) and build up the solution to the n variables.

  1. We create a two-dimensional array called dp with dimensions n+1 x val+1, where dp[i][j] represents the number of solutions to the equation with i variables and sum j.
  2. Since there is only one variable in the first row (i=1), the number of solutions to the equation is always 1. Thus, initialize the first row of dp with all 1’s.
  3. For each subsequent row (i > 1) and each column j, we calculate dp[i][j] as the sum of dp[i-1][j-k] for all possible values of k between 0 and j. Because, for each solution to the equation with i variables and sum j, we can obtain a solution to the equation with i-1 variables and sum j-k by subtracting k from one of the variables.
  4. After computing all values of dp[n][j], we return dp[n][val], which represents the number of non-negative integral solutions to the equation with n variables and sum val.

Here is the Java Implementation of above algorithm 

C++




#include <iostream>
using namespace std;
 
// Function to count the number of
// non-negative integral solutions
int Solutions(int n, int val)
{
    int dp[n + 1][val + 1];
    // Initialize the first row of the dp array dp[1][j] will have 1 solution for every j
    for (int i = 0; i <= val; i++) {
        dp[1][i] = 1;
    }
    // Compute the number of solutions for each i and j using previous solutions
    for (int i = 2; i <= n; i++) {
        for (int j = 0; j <= val; j++) {
            dp[i][j] = 0;
            for (int k = 0; k <= j; k++) {
                dp[i][j] += dp[i - 1][j - k];
            }
        }
    }
    // Return the solution for n variables and sum val
    return dp[n][val];
}
// Driver code
int main()
{
    int n = 5;
    int val = 20;
    // Function call
    cout << Solutions(n, val) << endl;
    return 0;
}


Java




// Java program to find the numbers
// of non negative integral solutions using bottom up
// approach
import java.io.*;
 
class GFG {
    // return number of non negative
    // integral solutions
    public static int countSolutions(int n, int val)
    {
        // Create a 2D array to store the number of
        // solutions dp[i][j] will store the number of
        // solutions for i variables and sum j
        int dp[][] = new int[n + 1][val + 1];
 
        // Initialize the first row of the dp array
        // dp[1][j] will have 1 solution for every j
        for (int i = 0; i <= val; i++) {
            dp[1][i] = 1;
        }
 
        // Compute the number of solutions for each i and j
        // using previous solutions
        for (int i = 2; i <= n; i++) {
            for (int j = 0; j <= val; j++) {
                dp[i][j] = 0;
                // For each k from 0 to j, add the number of
                // solutions from the previous row
                // dp[i][j] = dp[i-1][j] + dp[i-1][j-1] +
                // ... + dp[i-1][j-k]
                for (int k = 0; k <= j; k++) {
                    dp[i][j] += dp[i - 1][j - k];
                }
            }
        }
        // Return the solution for n variables and sum val
        return dp[n][val];
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 5;
        int val = 20;
 
        // function call
        System.out.println(countSolutions(n, val));
    }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Python3




def solutions(n, val):
    dp = [[0 for _ in range(val + 1)] for _ in range(n + 1)]
 
    # Initialize the first row of the dp array
    for i in range(val + 1):
        dp[1][i] = 1
 
    # Compute the number of solutions for each i and j using previous solutions
    for i in range(2, n + 1):
        for j in range(val + 1):
            dp[i][j] = 0
            for k in range(j + 1):
                dp[i][j] += dp[i - 1][j - k]
 
    # Return the solution for n variables and sum val
    return dp[n][val]
 
# Driver code
if __name__ == "__main__":
    n = 5
    val = 20
    # Function call
    print(solutions(n, val))


C#




using System;
 
class GFG
{
    // Function to return the number of non-negative integral solutions
    public static int CountSolutions(int n, int val)
    {
        // Create a 2D array to store the number of solutions
        // dp[i][j] will store the number of solutions for i variables and sum j
        int[,] dp = new int[n + 1, val + 1];
 
        // Initialize the first row of the dp array
        // dp[1][j] will have 1 solution for every j
        for (int i = 0; i <= val; i++)
        {
            dp[1, i] = 1;
        }
 
        // Compute the number of solutions for each i and j
        // using previous solutions
        for (int i = 2; i <= n; i++)
        {
            for (int j = 0; j <= val; j++)
            {
                dp[i, j] = 0;
                // For each k from 0 to j, add the number of solutions from the previous row
                // dp[i][j] = dp[i-1][j] + dp[i-1][j-1] + ... + dp[i-1][j-k]
                for (int k = 0; k <= j; k++)
                {
                    dp[i, j] += dp[i - 1, j - k];
                }
            }
        }
        // Return the solution for n variables and sum val
        return dp[n, val];
    }
 
    // Main method
    public static void Main(string[] args)
    {
        int n = 5;
        int val = 20;
 
        // Function call
        Console.WriteLine(CountSolutions(n, val));
    }
}


Javascript




// JavaScript program to find the numbers
// of non negative integral solutions using bottom up
// approach
 
// return number of non negative
// integral solutions
function countSolutions(n, val)
{
    // Create a 2D array to store the number of
    // solutions dp[i][j] will store the number of
    // solutions for i variables and sum j
    const dp = new Array(n + 1).fill(null).map(() => new Array(val + 1).fill(0));
     
    // Initialize the first row of the dp array
    // dp[1][j] will have 1 solution for every j
    for (let i = 0; i <= val; i++) {
        dp[1][i] = 1;
    }
     
    // Compute the number of solutions for each i and j
    // using previous solutions
    for (let i = 2; i <= n; i++) {
        for (let j = 0; j <= val; j++) {
            dp[i][j] = 0;
            // For each k from 0 to j, add the number of
            // solutions from the previous row
            // dp[i][j] = dp[i-1][j] + dp[i-1][j-1] +
            // ... + dp[i-1][j-k]
             
            for (let k = 0; k <= j; k++) {
                dp[i][j] += dp[i - 1][j - k];
            }
        }
    }
     
    // Return the solution for n variables and sum val
    return dp[n][val];
}
 
// Driver code
const n = 5;
const val = 20;
// function call
console.log(countSolutions(n, val));


Output

10626







Complexity Analysis 

Time Complexity : O(n * val^2), where n is the number of variables and val is the given sum.

Auxiliary Space : O( n * val), creating a 2D array of size (n + 1) * (val + 1).



Similar Reads

Number of non-negative integral solutions of a + b + c = n
Given a number n, find the number of ways in which we can add 3 non-negative integers so that their sum is n.Examples : Input : n = 1 Output : 3 There are three ways to get sum 1. (1, 0, 0), (0, 1, 0) and (0, 0, 1) Input : n = 2 Output : 6 There are six ways to get sum 2. (2, 0, 0), (0, 2, 0), (0, 0, 2), (1, 1, 0) (1, 0, 1) and (0, 1, 1) Input : n
7 min read
Number of integral solutions for equation x = b*(sumofdigits(x)^a)+c
Given a, b and c which are part of the equation x = b * ( sumdigits(x) ^ a ) + c.Where sumdigits(x) determines the sum of all digits of the number x. The task is to find out all integer solutions for x that satisfy the equation and print them in increasing order. Given that, 1&lt;=x&lt;=109Examples: Input: a = 3, b = 2, c = 8 Output: 10 2008 13726
9 min read
Number of integral solutions of the equation x1 + x2 +.... + xN = k
Given N and K. The task is to count the number of the integral solutions of a linear equation having N variable as given below: x1 + x2+ x3...+ xN-1+...+xN = K Examples: Input: N = 3, K = 3Output: 10Explanation: Possible solutions are: (1,1,1),(1,0,2),(2,0,1),(1,2,0),(2,1,0),(0,1,2),(0,2,1),(3,0,0),(0,3,0),(0,0,3) Input: N = 2, K = 2Output: 3 Appro
5 min read
Find an integral solution of the non-linear equation 2X + 5Y = N
Given an integer N representing a non-linear equation of the form 2X + 5Y = N, the task is to find an integral pair (X, Y) that satisfies the given equation. If multiple solutions exist, then print any one of them. Otherwise, print -1. Examples: Input: N = 29 Output: X = 2, Y = 2 Explanation: Since, 22 + 52 = 29 Therefore, X = 2 and Y = 2 satisfy t
8 min read
Find initial integral solution of Linear Diophantine equation if finite solution exists
Given three integers a, b, and c representing a linear equation of the form: ax + by = c. The task is to find the initial integral solution of the given equation if a finite solution exists. A Linear Diophantine equation (LDE) is an equation with 2 or more integer unknowns and the integer unknowns are each to at most degree of 1. Linear Diophantine
8 min read
Find the integral roots of a given Cubic equation
Given 5 integers say A, B, C, D, and E which represents the cubic equation [Tex]f(x) = A*x^{3} + B*x^{2} + C*x + D = E [/Tex], the task is to find the integral solution for this equation. If there doesn't exist any integral solution then print "NA".Examples: Input: A = 1, B = 0, C = 0, D = 0, E = 27 Output: 3Input: A = 1, B = 0, C = 0, D = 0, E = 1
7 min read
Maximum integral co-ordinates with non-integer distances
Given a maximum limit of x - coordinate and y - coordinate, we want to calculate a set of coordinates such that the distance between any two points is a non-integer number. The coordinates (i, j) chosen should be of range 0&lt;=i&lt;=x and 0&lt;=j&lt;=y. Also, we have to maximize the set. Examples: Input : 4 4 Output : 0 4 1 3 2 2 3 1 4 0 Explanati
5 min read
Quadratic equation whose roots are reciprocal to the roots of given equation
Given three integers A, B, and C representing the coefficients of a quadratic equation Ax2 + Bx + C = 0, the task is to find the quadratic equation whose roots are reciprocal to the roots of the given equation. Examples: Input: A = 1, B = -5, C = 6 Output: (6)x^2 +(-5)x + (1) = 0Explanation: The given quadratic equation x2 - 5x + 6 = 0.Roots of the
4 min read
Quadratic equation whose roots are K times the roots of given equation
Given three integers A, B, and C representing the coefficients of a quadratic equation Ax2 + Bx + C = 0 and a positive integer K, the task is to find the coefficients of the quadratic equation whose roots are K times the roots of the given equation. Examples: Input: A = 1, B = 2, C = 1, K = 2Output: 1 4 4Explanation:The given quadratic equation x2
4 min read
Draw circle using polar equation and Bresenham's equation
In this article, we will discuss how to draw circles using Bresenham Equation and Polar Equation. Circle Drawing AlgorithmIt is not easy to display a continuous smooth arc on the computer screen as our computer screen is made of pixels organized in matrix form. So, to draw a circle on a computer screen it should always choose the nearest pixels fro
19 min read