📌  相关文章
📜  在N次抛硬币中获得K个头的可能性

📅  最后修改于: 2021-04-28 00:08:56             🧑  作者: Mango

给定两个整数NR。任务是计算在n次连续抛掷中准确获得r个头部的概率。
普通硬币在每次抛掷时正面或反面的几率均等。

例子:

Input : N = 1, R = 1 
Output : 0.500000 

Input : N = 4, R = 3
Output : 0.250000 

方法
可以使用以下公式计算在N次掷硬币中获得K个头的可能性:
[\frac{1}{2^n} * \frac{n!}{ r! * (n-r)!}]

下面是上述方法的实现:

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


Python3
# 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


Javascript


输出:
0.250000

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