Probability that the pieces of a broken stick form a n sided polygon in C++


We are given with the stick of any length and that stick can be broken randomly into n pieces which can be of type integer or floating point and the task is to find whether the broken pieces can form a n sided polygon.

We can calculate the probability by applying the formula

$$P(E^{\prime})=1-P(E)=1-\frac{n}{2^{n-1}}$$

Where, n is the number of pieces generated by breaking the stick into parts.

Input 

length = 10 , pieces = 4

Output 

probability is : 0.5

Explanation − given with length of size 10 cm and it is broken into 4 parts

Input 

length = 5 , pieces = 3

Output 

probability is : 0.25

Explanation − given with length of size 5 cm and it is broken into 3 parts

Approach used in the below program is as follows

  • Input the length of the stick with number of pieces it can be broken into

  • Apply the formula to calculate the probability

  • Print the result

Algorithm

Start
Step 1→ Declare function to calculate the probability
   double probab(unsigned len, unsigned pieces)
      declare unsigned a = (1 << (pieces-1))
      return 1.0 - ((double)pieces) / ((double)a)
step 2→ In main()
   Declare unsigned pieces = 4, len = 10
   Call probab(len, pieces)
Stop

Example

 Live Demo

#include<iostream>
using namespace std;
//function to calculate probability
double probab(unsigned len, unsigned pieces){
   unsigned a = (1 < (pieces-1));
   return 1.0 - ((double)pieces) / ((double)a);
}
int main(){
   unsigned pieces = 4, len = 10;
   cout <<"probability is : "<<probab(len, pieces);
   return 0;
}

Output

If run the above code it will generate the following output −

probability is : 0.5

Updated on: 13-Aug-2020

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements