Count number of ways to divide a number in 4 parts

Given a positive integer n, find number of ways to divide n in four parts or represent n as sum of four positive integers. Here n varies from 0 to 5000.

Examples :

Input:  n =  5
Output: 1
There is only one way (1, 1, 1, 2)

Input:  n =  6
Output: 2
There are two ways (1, 1, 1, 3) and 
(1, 1, 2, 2)

Input:  n =  8
Output: 5
There are five ways (2, 2, 2, 2), (1, 1, 1, 5),
(1, 1, 3, 3), (1, 1, 2, 4) and (1, 2, 2, 3)




Method 1 (Simple Solution) Run four nested loops to generate all possible different quadruplet. Below is C++ implementation of the simple algorithm.
Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Simple C++ program to count number of ways to
// represent a number n as sum of four.
#include<bits/stdc++.h>
using namespace std;
  
// Returns count of ways
int countWays(int n)
{
    int counter = 0; // Initialize result
  
    // Generate all possible quadruplet and increment
    // counter when sum of a quadruplet is equal to n
    for (int i = 1; i < n; i++)
        for (int j = i; j < n; j++)
            for (int k = j; k < n; k++)
                for (int l = k; l < n; l++)
                    if (i + j + k + l == n)
                       counter++;
    return counter;
}
  
// Driver program
int main()
{
   int n = 8;
   cout << countWays(n);
   return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Simple Java  program to count number of ways to 
// represent a number n as sum of four. 
  
import java.io.*;
  
class GFG {
      
// Returns count of ways 
static int countWays(int n) 
    int counter = 0; // Initialize result 
  
    // Generate all possible quadruplet and increment 
    // counter when sum of a quadruplet is equal to n 
    for (int i = 1; i < n; i++) 
        for (int j = i; j < n; j++) 
            for (int k = j; k < n; k++) 
                for (int l = k; l < n; l++) 
                    if (i + j + k + l == n) 
                    counter++; 
    return counter; 
  
// Driver program 
      
    public static void main (String[] args) {
        int n = 8
        System.out.println (countWays(n));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# A Simple python3 program to count 
# number of ways to represent a number
# n as sum of four.
  
# Returns count of ways
def countWays(n):
  
    counter = 0 # Initialize result
  
    # Generate all possible quadruplet 
    # and increment counter when sum of
    # a quadruplet is equal to n
    for i in range(1, n):
        for j in range(i, n):
            for k in range(j, n):
                for l in range(k, n):
                    if (i + j + k + l == n):
                        counter += 1
    return counter
  
# Driver Code
if __name__ == "__main__":
  
    n = 8
    print (countWays(n))
  
# This code is contributed by ita_c

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Simple C# program to count number 
// of ways to represent a number n as 
// sum of four. 
using System;
  
class GFG
{
          
// Returns count of ways 
static int countWays(int n) 
    int counter = 0; // Initialize result 
  
    // Generate all possible quadruplet 
    // and increment counter when sum of 
    // a quadruplet is equal to n 
    for (int i = 1; i < n; i++) 
        for (int j = i; j < n; j++) 
            for (int k = j; k < n; k++) 
                for (int l = k; l < n; l++) 
                    if (i + j + k + l == n) 
                    counter++; 
    return counter; 
  
// Driver Code 
static public void Main ()
{
    int n = 8; 
    Console.WriteLine(countWays(n)); 
}
}
  
// This code is contributed by Sachin

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// A Simple PHP program to count
// number of ways to represent 
// a number n as sum of four.
  
// Returns count of ways
function countWays($n)
{
    // Initialize result
    $counter = 0;
  
    // Generate all possible quadruplet 
    // and increment counter when sum 
    // of a quadruplet is equal to n
    for ($i = 1; $i < $n; $i++)
        for ( $j = $i; $j < $n; $j++)
            for ($k = $j; $k < $n; $k++)
                for ( $l = $k; $l < $n; $l++)
                    if ($i + $j + $k + $l == $n)
                    $counter++;
    return $counter;
}
  
// Driver Code
$n = 8;
echo countWays($n);
      
// This code is contributed by m_kit
?>

chevron_right



Output :

5

Time complexity of above solution is O(n4)



Method 2 (Uses Dynamic Programming)
The idea is based on below recursive solution.

countWays(n, parts, nextPart) = ∑countWays(n, parts, i)
                          nextPart <= i  Input number
parts    --> Count of parts of n. Initially parts = 4
nextPart --> Starting point for next part to be tried
             We try for all values from nextPart to n.

We initially call the function as countWays(n, 4, 1)
 

Below is Dynamic Programming based on solution of above idea.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Dynamic Programming based solution to count number
// of ways to represent n as sum of four numbers
#include<bits/stdc++.h>
using namespace std;
int dp[5001][5001][5];
  
// "parts" is number of parts left, n is the value left
// "nextPart" is starting point from where we start trying
// for next part.
int countWaysUtil(int n, int parts, int nextPart)
{
    // Base cases
    if (parts == 0 && n == 0) return 1;
    if (n <= 0 || parts <= 0) return 0;
  
    // If this subproblem is already solved
    if (dp[n][nextPart][parts] != -1)
       return dp[n][nextPart][parts];
  
    int ans = 0; // Initialize result
  
    // Count number of ways for remaining number n-i
    // remaining parts "parts-1", and for all part
    // varying from 'nextPart' to 'n'
    for (int i = nextPart; i <= n; i++)
        ans += countWaysUtil(n-i, parts-1, i);
  
    // Store computed answer in table and return
    // result
    return (dp[n][nextPart][parts] = ans);
}
  
// This function mainly initializes dp table and
// calls countWaysUtil()
int countWays(int n)
{
    memset(dp, -1, sizeof(dp));
    return countWaysUtil(n, 4, 1);
}
  
// Driver program
int main()
{
   int n = 8;
   cout << countWays(n) << endl;
   return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# A Dynamic Programming based solution 
# to count number of ways to represent 
# n as sum of four numbers 
  
dp = [[[-1 for i in range(5)] 
           for i in range(501)]
           for i in range(501)] 
  
# "parts" is number of parts left, n is 
# the value left "nextPart" is starting 
# point from where we start trying 
# for next part. 
def countWaysUtil(n, parts, nextPart):
      
    # Base cases 
    if (parts == 0 and n == 0):
        return 1
    if (n <= 0 or parts <= 0):
        return 0
  
    # If this subproblem is already solved 
    if (dp[n][nextPart][parts] != -1):
        return dp[n][nextPart][parts]
  
    ans = 0 # Initialize result 
  
    # Count number of ways for remaining 
    # number n-i remaining parts "parts-1", 
    # and for all part varying from 
    # 'nextPart' to 'n' 
    for i in range(nextPart, n + 1): 
        ans += countWaysUtil(n - i, parts - 1, i) 
  
    # Store computed answer in table 
    # and return result
    dp[n][nextPart][parts] = ans 
    return (ans)
  
# This function mainly initializes dp 
# table and calls countWaysUtil() 
def countWays(n):
    return countWaysUtil(n, 4, 1)
  
# Driver Code
n = 8
print(countWays(n))
  
# This code is contributed 
# by sahishelangia

chevron_right



Output :

5

Time complexity of this solution is O(n3). There are Θ(n2) entries, every entry is filled only once and filling an entry takes O(n) time.



Method 3 (A O(n2 Log n) Solution)
We can use the solution discussed in this post to find all quadruplets.



Thanks to Gaurav Ahirwar for suggesting above solutions.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up