Probability of getting K heads in N coin tosses
Last Updated :
15 Dec, 2022
Given two integers N and R. The task is to calculate the probability of getting exactly r heads in n successive tosses.
A fair coin has an equal probability of landing a head or a tail on each toss.
Examples:
Input : N = 1, R = 1
Output : 0.500000
Input : N = 4, R = 3
Output : 0.250000
Approach
Probability of getting K heads in N coin tosses can be calculated using below formula of binomial distribution of probability:
where p = probability of getting head and q = probability of getting tail. p and q both are 1/2. So the equation becomes
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int fact( int n)
{
int res = 1;
for ( int i = 2; i <= n; i++)
res = res * i;
return res;
}
double count_heads( int n, int r)
{
double output;
output = fact(n) / (fact(r) * fact(n - r));
output = output / ( pow (2, n));
return output;
}
int main()
{
int n = 4, r = 3;
cout << count_heads(n, r);
return 0;
}
|
Java
import java.io.*;
class GFG{
static int fact( int n)
{
int res = 1 ;
for ( int i = 2 ; i <= n; i++)
res = res * i;
return res;
}
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;
}
public static void main(String[] args)
{
int n = 4 , r = 3 ;
System.out.print(count_heads(n, r));
}
}
|
Python3
def fact(n):
res = 1
for i in range ( 2 , n + 1 ):
res = res * i
return res
def count_heads(n, r):
output = fact(n) / (fact(r) * fact(n - r))
output = output / ( pow ( 2 , n))
return output
n = 4
r = 3
print (count_heads(n, r))
|
C#
using System;
public class GFG{
static int fact( int n)
{
int res = 1;
for ( int i = 2; i <= n; i++)
res = res * i;
return res;
}
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;
}
public static void Main(String[] args)
{
int n = 4, r = 3;
Console.Write(count_heads(n, r));
}
}
|
Javascript
<script>
function fact(n)
{
var res = 1;
for ( var i = 2; i <= n; i++)
res = res * i;
return res;
}
function count_heads(n, r)
{
var output;
output = fact(n) / (fact(r) * fact(n - r));
output = output / (Math.pow(2, n));
return output;
}
var n = 4, r = 3;
document.write(count_heads(n, r));
</script>
|
Time Complexity: In this implementation, we have to calculate factorial based on the value n, so time complexity would be O(n)
Auxiliary Space: In this implementation, we are not using any extra space, so auxiliary space required is O(1)
Share your thoughts in the comments
Please Login to comment...