The Wayback Machine - https://web.archive.org/web/20240624070330/https://www.geeksforgeeks.org/print-all-possible-ways-to-write-n-as-sum-of-two-or-more-positive-integers/
Open In App

Print all possible ways to write N as sum of two or more positive integers

Last Updated : 02 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N, the task is to print all the possible ways in which N can be written as the sum of two or more positive integers.
Examples: 
 

Input: N = 4 
Output: 
1 1 1 1 
1 1 2 
1 3 
2 2 
Input: N = 3 
Output: 
1 1 1 
1 2 
 

 

Approach: The idea is to use recursion to solve this problem. The idea is to consider every integer from 1 to N such that the sum N can be reduced by this number at each recursive call and if at any recursive call N reduces to zero then we will print the answer stored in the vector. Below are the steps for recursion: 
 

  1. Get the number N whose sum has to be broken into two or more positive integers.
  2. Recursively iterate from value 1 to N as index i:
  • Base Case: If the value called recursively is 0, then print the current vector as this is one of the ways to broke N into two or more positive integers. 
     
if (n == 0)
    printVector(arr);
  • Recursive Call: If the base case is not met, then Recursively iterate from [i, N – i]. Push the current element j into vector(say arr) and recursively iterate for the next index and after this recursion ends then pop the element j inserted previously: 
     
for j in range[i, N]:
    arr.push_back(j);
    recursive_function(arr, j + 1, N - j);
    arr.pop_back(j);   

Below is the implementation of the above approach:
 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the values stored
// in vector arr
void printVector(vector<int>& arr)
{
    if (arr.size() != 1) {
 
        // Traverse the vector arr
        for (int i = 0; i < arr.size(); i++) {
            cout << arr[i] << " ";
        }
        cout << endl;
    }
}
 
// Recursive function to print different
// ways in which N can be written as
// a sum of at 2 or more positive integers
void findWays(vector<int>& arr, int i, int n)
{
    // If n is zero then print this
    // ways of breaking numbers
    if (n == 0)
        printVector(arr);
 
    // Start from previous element
    // in the representation till n
    for (int j = i; j <= n; j++) {
 
        // Include current element
        // from representation
        arr.push_back(j);
 
        // Call function again
        // with reduced sum
        findWays(arr, j, n - j);
 
        // Backtrack to remove current
        // element from representation
        arr.pop_back();
    }
}
 
// Driver Code
int main()
{
    // Given sum N
    int n = 4;
 
    // To store the representation
    // of breaking N
    vector<int> arr;
 
    // Function Call
    findWays(arr, 1, n);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to print the values stored
// in vector arr
static void printVector(ArrayList<Integer> arr)
{
    if (arr.size() != 1)
    {
         
        // Traverse the vector arr
        for(int i = 0; i < arr.size(); i++)
        {
            System.out.print(arr.get(i) + " ");
        }
        System.out.println();
    }
}
 
// Recursive function to print different
// ways in which N can be written as
// a sum of at 2 or more positive integers
static void findWays(ArrayList<Integer> arr,
                     int i, int n)
{
     
    // If n is zero then print this
    // ways of breaking numbers
    if (n == 0)
        printVector(arr);
 
    // Start from previous element
    // in the representation till n
    for(int j = i; j <= n; j++)
    {
         
        // Include current element
        // from representation
        arr.add(j);
 
        // Call function again
        // with reduced sum
        findWays(arr, j, n - j);
 
        // Backtrack to remove current
        // element from representation
        arr.remove(arr.size() - 1);
    }
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given sum N
    int n = 4;
     
    // To store the representation
    // of breaking N
    ArrayList<Integer> arr = new ArrayList<Integer>();
     
    // Function call
    findWays(arr, 1, n);
}
}
 
// This code is contributed by offbeat


Python3




# Python3 program for the above approach
 
# Function to print the values stored
# in vector arr
def printVector(arr):
 
    if (len(arr) != 1):
 
        # Traverse the vector arr
        for i in range(len(arr)):
            print(arr[i], end = " ")
        print()   
 
# Recursive function to print different
# ways in which N can be written as
# a sum of at 2 or more positive integers
def findWays(arr, i, n):
 
    # If n is zero then print this
    # ways of breaking numbers
    if (n == 0):
        printVector(arr)
 
    # Start from previous element
    # in the representation till n
    for j in range(i, n + 1):
 
        # Include current element
        # from representation
        arr.append(j)
 
        # Call function again
        # with reduced sum
        findWays(arr, j, n - j)
 
        # Backtrack to remove current
        # element from representation
        del arr[-1]
         
# Driver Code
if __name__ == '__main__':
 
    # Given sum N
    n = 4
 
    # To store the representation
    # of breaking N
    arr = []
 
    # Function Call
    findWays(arr, 1, n)
 
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to print the values stored
// in vector arr
static void printList(List<int> arr)
{
    if (arr.Count != 1)
    {
         
        // Traverse the vector arr
        for(int i = 0; i < arr.Count; i++)
        {
            Console.Write(arr[i] + " ");
        }
        Console.WriteLine();
    }
}
 
// Recursive function to print different
// ways in which N can be written as
// a sum of at 2 or more positive integers
static void findWays(List<int> arr,
                     int i, int n)
{
     
    // If n is zero then print this
    // ways of breaking numbers
    if (n == 0)
        printList(arr);
 
    // Start from previous element
    // in the representation till n
    for(int j = i; j <= n; j++)
    {
         
        // Include current element
        // from representation
        arr.Add(j);
 
        // Call function again
        // with reduced sum
        findWays(arr, j, n - j);
 
        // Backtrack to remove current
        // element from representation
        arr.RemoveAt(arr.Count - 1);
    }
}
 
// Driver code
public static void Main(String[] args)
{
     
    // Given sum N
    int n = 4;
     
    // To store the representation
    // of breaking N
    List<int> arr = new List<int>();
     
    // Function call
    findWays(arr, 1, n);
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript program for the above approach
 
// Function to print the values stored
// in vector arr
function printVector(arr)
{
    if (arr.length != 1) {
 
        // Traverse the vector arr
        for (var i = 0; i < arr.length; i++) {
            document.write( arr[i] + " ");
        }
        document.write("<br>");
    }
}
 
// Recursive function to print different
// ways in which N can be written as
// a sum of at 2 or more positive integers
function findWays(arr, i, n)
{
    // If n is zero then print this
    // ways of breaking numbers
    if (n == 0)
        printVector(arr);
 
    // Start from previous element
    // in the representation till n
    for (var j = i; j <= n; j++) {
 
        // Include current element
        // from representation
        arr.push(j);
 
        // Call function again
        // with reduced sum
        findWays(arr, j, n - j);
 
        // Backtrack to remove current
        // element from representation
        arr.pop();
    }
}
 
// Driver Code
// Given sum N
var n = 4;
// To store the representation
// of breaking N
var arr = [];
// Function Call
findWays(arr, 1, n);
 
</script>


Output: 

1 1 1 1 
1 1 2 
1 3 
2 2

 

Time Complexity: O(2N) 
Auxiliary Space: O(N2)
 



Similar Reads

Ways to write N as sum of two or more positive integers | Set-2
Given a number N, the task is to find the number of ways N can be partitioned, i.e. the number of ways that N can be expressed as a sum of positive integers.Note: N should also be considered itself a way to express it as a sum of positive integers. Examples: Input: N = 5 Output: 7 5 can be partitioned in the following ways: 5 4 + 1 3 + 2 3 + 1 + 1
5 min read
Ways to write n as sum of two or more positive integers
For a given number n &gt; 0, find the number of different ways in which n can be written as a sum of two or more positive integers. Examples: Input : n = 5 Output : 6 Explanation : All possible six ways are : 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 Input : 4 Output : 4 Explanation : All possible four ways are : 3 + 1 2 + 2 2
6 min read
Number of ways in which N can be represented as the sum of two positive integers
Given a number N, the task is to find the number of unique ways in which N can be represented as a sum of two positive integers.Examples: Input: N = 7 Output: 3 (1 + 6), (2 + 5) and (3 + 4).Input: N = 200 Output: 100 Approach: The number of ways in which the number can be expressed as the sum of two positive integers are 1 + (N - 1), 2 + (N - 2), .
3 min read
Find all the possible remainders when N is divided by all positive integers from 1 to N+1
Given a large integer N, the task is to find all the possible remainders when N is divided by all the positive integers from 1 to N + 1. Examples: Input: N = 5 Output: 0 1 2 5 5 % 1 = 0 5 % 2 = 1 5 % 3 = 2 5 % 4 = 1 5 % 5 = 0 5 % 6 = 5 Input: N = 11 Output: 0 1 2 3 5 11 Naive approach: Run a loop from 1 to N + 1 and return all the unique remainders
5 min read
Min sum of set of positive integers so that sum of no two elements is K
Given two positive integers N and K. Create a set of size N containing distinct positive integers such that the sum of no two integers is K, the task is to find the minimum possible sum of the set that meets the above criteria. Since the answer may be large, print it modulo 10^9+7. Note: It is guaranteed that it is always possible to make a set tha
6 min read
Number of ways to write N as a sum of K non-negative integers
Given two positive integers N and K, the task is to count the number of ways to write N as a sum of K non-negative integers. Examples: Input: N = 2, K = 3 Output: 6 Explanation: The total ways in which 2 can be split into K non-negative integers are: 1. (0, 0, 2) 2. (0, 2, 0) 3. (2, 0, 0) 4. (0, 1, 1) 5. (1, 0, 1) 6. (1, 1, 0) Input: N = 3, K = 2 O
15+ min read
Minimum product of k integers in an array of positive Integers
Given an array of n positive integers. We are required to write a program to print the minimum product of k integers of the given array. Examples:  Input : 198 76 544 123 154 675 k = 2Output : 9348We get minimum product after multiplying76 and 123.Input : 11 8 5 7 5 100 k = 4Output : 1400Recommended PracticeMinimum Product of k IntegersTry It!An ap
6 min read
Count numbers up to N that cannot be expressed as sum of at least two consecutive positive integers
Given a positive integer N, the task is to find the count of integers from the range [1, N] such that the integer cannot be expressed as sum of two or more consecutive positive integers. Examples: Input: N = 10Output: 4Explanation: The integers that cannot be expressed as sum of two or more consecutive integers are {1, 2, 4, 8}. Therefore, the coun
8 min read
Count of permutations of first N positive integers such that sum of any two consecutive numbers is prime
Find the number of permutations of first N positive integers such that the sum of any two consecutive numbers is prime where all the cyclic permutations are considered the same. Note: The sum of the first and last element must be prime as well. Example: Input: N = 6Output: 2Explanation: The two valid permutations are {1, 4, 3, 2, 5, 6} and {1, 6, 5
12 min read
Count even sum pairs possible by selecting two integers from two given ranges respectively
Given two positive integers X and Y, the task is to count pairs with even sum possible by choosing any integer from the range 1 to X and another integer from the range 1 to Y. Examples: Input : X = 2, Y = 3 Output : 3 Explanation : All such possible pairs are {1, 1}, {1, 3}, {2, 2}. Approach: Follow the steps below to solve the problem: Initialize
6 min read
three90RightbarBannerImg