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

C++Server Side ProgrammingProgramming

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


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


length = 10 , pieces = 4


probability is : 0.5

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


length = 5 , pieces = 3


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


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)


 Live Demo

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;


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

probability is : 0.5
Updated on 13-Aug-2020 07:23:38