Probability of getting at least K heads in N tosses of Coins | Naive approach in PHP 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
< ? php $ MAX = 21 ; $ fact = array_fill ( 0 , $ MAX , 0 ) ; function probability ( $ k , $ n ) { global $ fact ; $ ans = 0 ; for ( $ i = $ k ; $ i <= $ n ; ++ $ i ) $ ans += $ fact [ $ n ] / ( $ fact [ $ i ] * $ fact [ $ n - $ i ] ) ; $ ans = $ ans / ( 1 << $ n ) ; return $ ans ; } function precompute ( ) { global $ fact ; $ fact [ 0 ] = $ fact [ 1 ] = 1 ; for ( $ i = 2 ; $ i < 20 ; ++ $ i ) $ fact [ $ i ] = $ fact [ $ i - 1 ] * $ i ; } precompute ( ) ; echo number_format ( probability ( 2 , 3 ) , 6 ) . " STRNEWLINE " ; echo number_format ( probability ( 3 , 6 ) , 6 ) . " STRNEWLINE " ; echo number_format ( probability ( 12 , 18 ) , 6 ) ; ? >