Probability of getting at least K heads in N tosses of Coins | javascript Code for Probability of getting atleast K heads in N tosses of Coins ; 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
let fact ; function probability ( k , n ) { let ans = 0 , i ; for ( i = k ; i <= n ; ++ i ) ans += fact [ n ] / ( fact [ i ] * fact [ n - i ] ) ; ans = ans / ( 1 << n ) ; return ans ; } function precompute ( ) { fact [ 0 ] = fact [ 1 ] = 1 ; for ( let i = 2 ; i < 20 ; ++ i ) fact [ i ] = fact [ i - 1 ] * i ; } fact = Array ( 100 ) . fill ( 0 ) ; precompute ( ) ; document . write ( probability ( 2 , 3 ) + " " ) ; document . write ( probability ( 3 , 6 ) + " " ) ; document . write ( probability ( 12 , 18 ) . toFixed ( 6 ) + " " ) ;