Probability of getting at least K heads in N tosses of Coins | Naive approach in C ++ to find probability of at least k heads ; Returns probability of getting at least k heads in n tosses . ; Probability of getting exactly i heads out of n heads ; Note : 1 << n = pow ( 2 , n ) ; Preprocess all factorial only upto 19 , as after that it will overflow ; Driver code ; Probability of getting 2 head out of 3 coins ; Probability of getting 3 head out of 6 coins ; Probability of getting 12 head out of 18 coins
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  21 NEW_LINE double fact [ MAX ] ; double probability ( int k , int n ) { double ans = 0 ; for ( int i = k ; i <= n ; ++ i ) ans += fact [ n ] / ( fact [ i ] * fact [ n - i ] ) ; ans = ans / ( 1LL << n ) ; return ans ; } void precompute ( ) { fact [ 0 ] = fact [ 1 ] = 1 ; for ( int i = 2 ; i < 20 ; ++ i ) fact [ i ] = fact [ i - 1 ] * i ; } int main ( ) { precompute ( ) ; cout << probability ( 2 , 3 ) << " STRNEWLINE " ; cout << probability ( 3 , 6 ) << " STRNEWLINE " ; cout << probability ( 12 , 18 ) ; return 0 ; }