- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
To Continue Learning Please Login
Login with Google