📜  自然数的成分数

📅  最后修改于: 2021-06-25 13:21:29             🧑  作者: Mango

给定自然数n,请考虑将顺序考虑在内时可以将n表示为自然数之和的方式的数目。术语顺序不同的两个序列定义了其和的不同组成。
例子:

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

一个简单的解决方案是生成所有合成并对其进行计数。
使用组合学的概念,可以证明,当考虑阶数时,任何自然数n都将具有2 ^(n-1)个不同的组成

C++
// C++ program to find the total number of
// compositions of a natural number
#include
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


PHP


Javascript


输出:

8