原文:

给定两个整数 nr 。任务是计算连续投掷中准确获得 r 人头的概率。 一枚公平的硬币在每一次抛硬币时都有相等的概率落在头上或尾巴上。

示例:

input : n = 1, r = 1 
output : 0.500000 
input : n = 4, r = 3
output : 0.250000 

接近 n 次抛硬币中获得 k 个头像的概率可以使用以下公式计算:

下面是上述方法的实现:

c

#include 
using namespace std;
// function to calculate factorial
int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i  )
        res = res * i;
    return res;
}
// apply the formula
double count_heads(int n, int r)
{
    double output;
    output = fact(n) / (fact(r) * fact(n - r));
    output = output / (pow(2, n));
    return output;
}
// driver function
int main()
{
    int n = 4, r = 3;
    // call count_heads with n and r
    cout << count_heads(n, r);
    return 0;
}

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

class gfg{
// function to calculate factorial
static int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i  )
        res = res * i;
    return res;
}
// apply the formula
static double count_heads(int n, int r)
{
    double output;
    output = fact(n) / (fact(r) * fact(n - r));
    output = output / (math.pow(2, n));
    return output;
}
// driver function
public static void main(string[] args)
{
    int n = 4, r = 3;
    // call count_heads with n and r
    system.out.print(count_heads(n, r));
}
}
// this code is contributed by 29ajaykumar

python 3

# python3 program to find probability
# of getting k heads in n coin tosses
# function to calculate factorial
def fact(n):
    res = 1
    for i in range(2, n   1):
        res = res * i
    return res
# applying the formula
def count_heads(n, r):
    output = fact(n) / (fact(r) * fact(n - r))
    output = output / (pow(2, n))
    return output
# driver code
n = 4
r = 3
# call count_heads with n and r
print (count_heads(n, r))
# this code is contributed by pratik basu

c

using system;
public class gfg{
// function to calculate factorial
static int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i  )
        res = res * i;
    return res;
}
// apply the formula
static double count_heads(int n, int r)
{
    double output;
    output = fact(n) / (fact(r) * fact(n - r));
    output = output / (math.pow(2, n));
    return output;
}
// driver function
public static void main(string[] args)
{
    int n = 4, r = 3;
    // call count_heads with n and r
    console.write(count_heads(n, r));
}
}
// this code contributed by sapnasingh4991

java 描述语言


output: 

0.250000

时间复杂度:在此实现中,我们必须根据值 n 计算阶乘,因此时间复杂度将是 o(n) 辅助空间:在此实现中,我们没有使用任何额外的空间,因此所需的辅助空间是 o(1)