📜  选择球的方式,使得至少选择一个球

📅  最后修改于: 2021-06-25 17:05:04             🧑  作者: Mango

给定整数N ,任务是找到从给定的N个球中选择一些球的方法,以便至少选择一个球。由于该值可能很大,因此请打印模1000000007的值。
例子:

方法:N个球,每个球都可以选择或不选择。不同配置的总数为2 * 2 * 2 *…* N。我们可以写成2 N。但是必须从答案中减去没有选择球的状态。因此,结果将是(2 N – 1)%1000000007
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
const int MOD = 1000000007;
 
// Function to return the count of
// ways to choose the balls
int countWays(int n)
{
 
    // Calculate (2^n) % MOD
    int ans = 1;
    for (int i = 0; i < n; i++) {
        ans *= 2;
        ans %= MOD;
    }
 
    // Subtract the only where
    // no ball was chosen
    return ((ans - 1 + MOD) % MOD);
}
 
// Driver code
int main()
{
    int n = 3;
 
    cout << countWays(n);
 
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
static int MOD = 1000000007;
 
// Function to return the count of
// ways to choose the balls
static int countWays(int n)
{
 
    // Calculate (2^n) % MOD
    int ans = 1;
    for (int i = 0; i < n; i++)
    {
        ans *= 2;
        ans %= MOD;
    }
 
    // Subtract the only where
    // no ball was chosen
    return ((ans - 1 + MOD) % MOD);
}
 
// Driver code
public static void main(String[] args)
{
    int n = 3;
 
    System.out.println(countWays(n));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 implementation of the approach
 
MOD = 1000000007
 
# Function to return the count of
# ways to choose the balls
def countWays(n):
     
    # Return ((2 ^ n)-1) % MOD
    return (((2**n) - 1) % MOD)
 
# Driver code
n = 3
print(countWays(n))


C#
// C# implementation of the approach
using System;
     
class GFG
{
static int MOD = 1000000007;
 
// Function to return the count of
// ways to choose the balls
static int countWays(int n)
{
 
    // Calculate (2^n) % MOD
    int ans = 1;
    for (int i = 0; i < n; i++)
    {
        ans *= 2;
        ans %= MOD;
    }
 
    // Subtract the only where
    // no ball was chosen
    return ((ans - 1 + MOD) % MOD);
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 3;
 
    Console.WriteLine(countWays(n));
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:
7