原文:https://www . geesforgeks . org/由第一个 n 个自然数组成的集合的所有子集的乘积/

给定一个数 n ,任务是从由前 n 个自然数组成的集合的所有可能子集中找到所有元素的乘积。 例:

输入: n = 2 输出: 4 可能的子集有{{1}、{2}、{1,2}}。 子集内元素的乘积= {1} * {2} * {1 * 2} = 4 输入: n = 3 输出: 1296 可能的子集有{{1}、{2}、{3}、{1,2}、{1,3}、{2,3}、{1,2,3}} 子集内元素的乘积= 1 * 2 * 3 * (1 * 2) * (1

天真方法:一个简单的pg电子试玩链接的解决方案是生成前 n 个自然数的所有子集。然后对于每个子集,计算它的乘积,最后返回每个子集的总乘积。 高效方法:

  • 可以观察到,原始数组的每个元素在所有子集中出现 2(n–1)次。
  • 因此最终答案中任何元素arrit3】的贡献都将是
i * 2(n – 1)
  • 所以,所有子集的立方之和将是
12n-1 * 22n-1 * 32n-1......n2n-1

以下是上述方法的实现:

c

// c   implementation of the approach
#include 
using namespace std;
// function to find the product of all elements
// in all subsets in natural numbers from 1 to n
int product(int n)
{
    int ans = 1;
    int val = pow(2, n - 1);
    for (int i = 1; i <= n; i  ) {
        ans *= pow(i, val);
    }
    return ans;
}
// driver code
int main()
{
    int n = 2;
    cout << product(n);
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java implementation of the approach
class gfg {
    // function to find the product of all elements
    // in all subsets in natural numbers from 1 to n
    static int product(int n)
    {
        int ans = 1;
        int val = (int)math.pow(2, n - 1);
        for (int i = 1; i <= n; i  ) {
            ans *= (int)math.pow(i, val);
        }
        return ans;
    }
    // driver code
    public static void main (string[] args)
    {
        int n = 2;
        system.out.println(product(n));
    }
}
// this code is contributed by ankitrai01

python 3

# python3 implementation of the approach
# function to find the product of all elements
# in all subsets in natural numbers from 1 to n
def product(n) :
    ans = 1;
    val = 2 **(n - 1);
    for i in range(1, n   1) :
        ans *= (i**val);
    return ans;
# driver code
if __name__ == "__main__" :
    n = 2;
    print(product(n));
# this code is contributed by ankitrai01

c

// c# implementation of the approach
using system;
class gfg {
    // function to find the product of all elements
    // in all subsets in natural numbers from 1 to n
    static int product(int n)
    {
        int ans = 1;
        int val = (int)math.pow(2, n - 1);
        for (int i = 1; i <= n; i  ) {
            ans *= (int)math.pow(i, val);
        }
        return ans;
    }
    // driver code
    public static void main (string[] args)
    {
        int n = 2;
        console.writeline(product(n));
    }
}
// this code is contributed by ankitrai01

java 描述语言


output: 

4

时间复杂度: o(n*logn)

辅助空间: o(1)