The Wayback Machine - https://web.archive.org/web/20240616042753/https://www.geeksforgeeks.org/number-compositions-natural-number/
Open In App

Number of compositions of a natural number

Last Updated : 28 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a natural number n, find the number of ways in which n can be expressed as a sum of natural numbers when order is taken into consideration. Two sequences that differ in the order of their terms define different compositions of their sum. 
Examples: 
 

Input :  4
Output : 8
Explanation
All 8 position composition are:
4, 1+3, 3+1, 2+2, 1+1+2, 1+2+1, 2+1+1
and 1+1+1+1
Input : 8
Output : 128

 

A Simple Solution is to generate all compositions and count them.
Using the concept of combinatorics, it can be proved that any natural number n will have 2^(n-1) distinct compositions when order is taken into consideration.
 

One way to see why the answer is 2^(n-1) directly is to write n as a sum of 1s: 
n = 1 + 1 + 1 +…+ 1 (n times).
There are (n-1) plus signs between all 1s. For every plus sign we can choose to split ( by putting a bracket) at the point or not split. Therefore answer is 2^(n-1).
For example, n = 4 
No Split 
4 = 1 + 1 + 1 + 1 [We write as single 4]
Different ways to split once 
4 = (1) + (1 + 1 + 1) [We write as 1 + 3] 
4 = (1 + 1) + (1 + 1) [We write as 2 + 2] 
4 = (1 + 1 + 1) + (1) [We write as 3 + 1]
Different ways to split twice 
4 = (1) + (1 + 1) + (1) [We write as 1 + 2 + 1] 
4 = (1 + 1) + (1) + (1) [We write as 2 + 1 + 1] 
4 = (1) + (1) + (1 + 1) [We write as 1 + 1 + 2]
Different ways to split three times 
4 = (1) + (1) + (1) + (1) [We write as 1 + 1 + 1 + 1]
Since there are (n-1) plus signs between the n 1s, there are 2^(n-1) ways of choosing where to split the sum, and hence 2^(n-1) possible sums .

 

C++




// C++ program to find the total number of
// compositions of a natural number
#include<iostream>
using namespace std;
 
#define ull unsigned long long
 
ull countCompositions(ull n)
{
    // Return 2 raised to power (n-1)
    return (1L) << (n-1);
}
 
// Driver Code
int main()
{
    ull n = 4;
    cout << countCompositions(n) << "\n";
    return 0;
}


Java




// Java program to find
// the total number of
// compositions of a
// natural number
import java.io.*;
import java.util.*;
 
class GFG
{
public static int countCompositions(int n)
{
    // Return 2 raised
    // to power (n-1)
    return 1 << (n - 1);
}
 
// Driver Code
public static void main(String args[])
{
    int n = 4;
    System.out.print(countCompositions(n));
}
}
 
// This code is contributed by
// Akanksha Rai(Abby_akku)


Python




# Python code to find the total number of
# compositions of a natural number
def countCompositions(n):
 
    # function to return the total number
    # of composition of n
    return (2**(n-1))
 
# Driver Code
print(countCompositions(4))


C#




// C# program to find the
// total number of compositions
// of a natural number
using System;
 
class GFG
{
public static int countCompositions(int n)
{
    // Return 2 raised
    // to power (n-1)
    return 1 << (n - 1);
}
 
// Driver Code
public static void Main()
{
    int n = 4;
    Console.Write(countCompositions(n));
}
}
 
// This code is contributed by mits


Javascript




<script>
 
// javascript program to find
// the total number of
// compositions of a
// natural number
 
function countCompositions(n)
{
    // Return 2 raised
    // to power (n-1)
    return 1 << (n - 1);
}
 
// Driver Code
 
    var n = 4;
    document.write(countCompositions(n));
 
 
 
// This code is contributed by 29AjayKumar
</script>


PHP




<?php
// PHP program to find the
// total number of compositions
// of a natural number
 
function countCompositions($n)
{
    // Return 2 raised
    // to power (n-1)
    return ((1) << ($n - 1));
}
 
// Driver Code
$n = 4;
echo countCompositions($n), "\n";
     
// This code is contributed
// by ajit
?>


Output: 
 

8

This article is contributed by Sruti Rai .

 Approach#2: Recursion with Memoization

The code uses memoization to efficiently calculate the number of compositions of a given integer using positive integers. The main function, count_compositions_memo, initializes a memo dictionary, and calls the recursive function count_compositions to calculate the result. The count_compositions function uses memoization to avoid redundant calculations, and computes the number of compositions recursively by iterating over all possible values of the first element in the composition and adding up the number of compositions for the remaining sum.

Algorithm

1. Create a dictionary ‘memo’ to store previously computed values.
2. Define a recursive function ‘count_compositions’ which takes n as input.
3. If n == 0, return 1.
4. If n < 0, return 0.
5. If memo[n] is not None, return memo[n].
6. Set memo[n] to 0.
7. Loop from i = 1 to i = n:
a. Add count_compositions(n-i) to memo[n].
8. Return memo[n].
9. Call count_compositions(n) and return its value.

C++




#include <iostream>
#include <unordered_map> // include the unordered_map library for memoization
 
int count_compositions_memo(int n) {
    std::unordered_map<int, int> memo; // create a memoization table
    if (n == 0) {
        return 1; // base case: there is only one way to compose 0
    }
    if (n < 0) {
        return 0; // base case: there is no way to compose a negative number
    }
    if (memo.find(n) != memo.end()) {
        return memo[n]; // if n is in the memoization table, return its value
    }
    int count = 0;
    for (int i = 1; i <= n; i++) {
        count += count_compositions_memo(n - i); // recursively count the number of compositions
    }
    memo[n] = count; // store the computed value in the memoization table
    return count;
}
 
int main() {
    int n = 4;
    std::cout << count_compositions_memo(n) << std::endl;
    return 0;
}


Java




import java.util.HashMap;
import java.util.Map;
 
public class CompositionCount {
 
    // Function to count compositions with memoization
    public static int countCompositionsMemo(int n) {
        // Create a memoization table using a HashMap
        Map<Integer, Integer> memo = new HashMap<>();
         
        // Base case: there is only one way to compose 0
        if (n == 0) {
            return 1;
        }
         
        // Base case: there is no way to compose a negative number
        if (n < 0) {
            return 0;
        }
         
        // If n is in the memoization table, return its value
        if (memo.containsKey(n)) {
            return memo.get(n);
        }
         
        int count = 0;
        // Recursively count the number of compositions
        for (int i = 1; i <= n; i++) {
            count += countCompositionsMemo(n - i);
        }
         
        // Store the computed value in the memoization table
        memo.put(n, count);
         
        return count;
    }
 
    public static void main(String[] args) {
        int n = 4;
        // Calculate and print the number of compositions for n
        System.out.println(countCompositionsMemo(n));
    }
}


Python3




def count_compositions_memo(n):
    memo = {}
    def count_compositions(n):
        if n == 0:
            return 1
        if n < 0:
            return 0
        if n in memo:
            return memo[n]
        memo[n] = 0
        for i in range(1,n+1):
            memo[n] += count_compositions(n-i)
        return memo[n]
    return count_compositions(n)
 
n=4
print(count_compositions_memo(n))


C#




using System;
using System.Collections.Generic;
 
class Program {
    static int
    CountCompositionsMemo(int n, Dictionary<int, int> memo)
    {
        if (n == 0) {
            return 1; // base case: there is only one way to
                      // compose 0
        }
        if (n < 0) {
            return 0; // base case: there is no way to
                      // compose a negative number
        }
        if (memo.ContainsKey(n)) {
            return memo[n]; // if n is in the memoization
                            // table, return its value
        }
        int count = 0;
        for (int i = 1; i <= n; i++) {
            count += CountCompositionsMemo(
                n - i, memo); // recursively count the
                              // number of compositions
        }
        memo[n] = count; // store the computed value in the
                         // memoization table
        return count;
    }
 
    static int CountCompositions(int n)
    {
        Dictionary<int, int> memo
            = new Dictionary<int, int>();
        return CountCompositionsMemo(n, memo);
    }
 
    static void Main()
    {
        int n = 4;
        Console.WriteLine(CountCompositions(n));
    }
}


Javascript




// Function to count compositions with memoization
function countCompositionsMemo(n) {
    // Create a memoization table using a Map
    const memo = new Map();
 
    // Base case: there is only one way to compose 0
    if (n === 0) {
        return 1;
    }
 
    // Base case: there is no way to compose a negative number
    if (n < 0) {
        return 0;
    }
 
    // If n is in the memoization table, return its value
    if (memo.has(n)) {
        return memo.get(n);
    }
 
    let count = 0;
    // Recursively count the number of compositions
    for (let i = 1; i <= n; i++) {
        count += countCompositionsMemo(n - i);
    }
 
    // Store the computed value in the memoization table
    memo.set(n, count);
 
    return count;
}
 
// Example usage
const n = 4;
// Calculate and print the number of compositions for n
console.log(countCompositionsMemo(n));


Output

8


Time complexity: O(n^2)
Auxiliary Space: O(n)



Similar Reads

Greatest divisor which divides all natural number in range [L, R]
Given two integers L and R, the task is to find the greatest divisor that divides all the natural numbers in the range [L, R].Examples: Input: L = 3, R = 12 Output: 1Input: L = 24, R = 24 Output: 24 Approach: For a range of consecutive integer elements, there are two cases: If L = R then the answer will L.If L &lt; R then all consecutive natural nu
3 min read
Number of M-length sorted arrays that can be formed using first N natural numbers
Given two numbers N and M, the task is to find the number of sorted arrays that can be formed of size M using first N natural numbers, if each number can be taken any number of times. Examples: Input: N = 4, M = 2Output: 10Explanation: All such possible arrays are {1, 1}, {1, 2}, {1, 2}, {1, 4}, {2, 2}, {2, 3}, {2, 4}, {3, 3}, {3, 4}, {4, 4}. Input
15+ min read
Number of distinct prime factors of first n natural numbers
In this article, we study an optimized way to calculate the distinct prime factorization up to n natural number using O O(n*log n) time complexity with pre-computation allowed.Prerequisites: Sieve of Eratosthenes, Least prime factor of numbers till n. Key Concept: Our idea is to store the Smallest Prime Factor(SPF) for every number. Then to calcula
9 min read
Sum of first N natural numbers by taking powers of 2 as negative number
Given a number N ( maybe up to 10^9 ). The task is to find the sum of first N natural number taking powers of 2 as a negative number.Examples: Input: N = 4 Output: -4 - 1 - 2 + 3 - 4 = -4 1, 2, and 4 are the powers of two. Input: N = 5 Output: 1 Approach: An efficient solution is to store the powers of two in an array and then store presum of this
8 min read
Find the k-th smallest divisor of a natural number N
You're given a number N and a number K. Our task is to find the kth smallest divisor of N.Examples: Input : N = 12, K = 5 Output : 6 The divisors of 12 after sorting are 1, 2, 3, 4, 6 and 12. Where the value of 5th divisor is equal to 6. Input : N = 16, K 2 Output : 2 Simple Approach: A simple approach is to run a loop from 1 to √N and find all fac
10 min read
Number of pairs from the first N natural numbers whose sum is divisible by K
Given the integer values of N and K. The task is to find the number of pairs from the set of natural numbers up to N{1, 2, 3......N-1, N} whose sum is divisible by K. Note : 1 &lt;= K &lt;= N &lt;= 10^6.Examples: Input : N = 10, K = 5 Output : 9 Explanation : The possible pairs whose sum is divisible by 5 are (1, 4), (1, 9), (6, 4), (6, 9), (2, 3),
14 min read
Find the number of sub arrays in the permutation of first N natural numbers such that their median is M
Given an array arr[] containing the permutation of first N natural numbers and an integer M ? N. The task is to find the number of sub-arrays such that the median of the sequence is M. The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence i
7 min read
Partition first N natural number into two sets such that their sum is not coprime
Given an integer N, the task is to partition the first N natural numbers in two non-empty sets such that the sum of these sets is not coprime to each other. If it is possible then find the possible partition then print -1 else print the sum of elements of both sets.Examples: Input: N = 5 Output: 10 5 {1, 2, 3, 4} and {5} are the valid partitions.In
4 min read
Count set bits in the Kth number after segregating even and odd from N natural numbers
Given two integers N and K, the task is to find the count of set bits in the Kth number in the Odd-Even sequence made of the number from the range [1, N]. The Odd-Even sequence first contains all the odd numbers from 1 to N and then all the even numbers from 1 to N.Examples: Input: N = 8, K = 4 Output: 3 The sequence is 1, 3, 5, 7, 2, 4, 6 and 8. 4
6 min read
Number of valid indices in the permutation of first N natural numbers
Given a permutation P of first N natural numbers. The task is to find the number of i's such that Pi ? Pj for all 1 ? j ? i in the permutation of first N natural numbers.Examples: Input: arr[] = {4, 2, 5, 1, 3} Output: 3 0, 1 and 3 are such indices.Input: arr[] = {4, 3, 2, 1} Output: 4 Approach: For i = 1, ..., N, define Mi = min{ Pj, 1 ? j ? i}. N
5 min read