- 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
Maximum number of dots after throwing a dice N times in C++
Given the task is to calculate the maximum number of dots that can be expected after throwing a dice N times having M faces.
The first face of the dice contains 1 dot, the second face has 2 dots and so on. Likewise the M-th face contains M number of dots.
The probability of appearance of each face becomes 1/M.
Let’s now understand what we have to do using an example −
Input − M=2, N=3
Output − 1.875
Explanation − The dice has 2 sides = {1, 2}
If the dice is thrown 3 times then the sample space will be = MN = 23
{(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2,) (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2,)} Maximum number in (1, 1, 1) = 1 Maximum number in (1, 1, 2) = 2 Maximum number in (1, 2, 1) = 2 Maximum number in (1, 2, 2) = 2 Maximum number in (2, 1, 1) = 2 Maximum number in (2, 1, 2) = 2 Maximum number in (2, 2, 1) = 2 Maximum number in (2, 2, 2) = 2 Probability of each case = 1/23 = 0.125 Therefore, expectation of maximum number = (1+2+2+2+2+2+2+2) * (0.125) = 1.875
Input − M=2, N=2
Output − 1.75
Approach used in the below program as follows
The maximum number of cases in which a number can occur can be found using its previous number by using the formula − iN – (i-1)N.
For example if M=4 and N=2, the total number of cases in which maximum = 4 will be 42 – (4-1)2 = 7.
So the final answer will be applying this formula on every element from 1 to M −
(i * (iN – (i - 1)N )) / MN and adding them up.
In function MaxExpect() initialize a variable max =0 of type double to store the sum.
Then loop from i=M till i>0
Inside the loop apply the above stated formula and keep adding all the resultant values into the variable max.
Example
#include <bits/stdc++.h> using namespace std; double MaxExpect(double M, double N){ double max = 0.0, i; for (i = M; i; i--) /*formula to find maximum number and sum of maximum numbers*/ max += (pow(i / M, N) - pow((i - 1) / M, N)) * i; return max; } int main(){ double M = 2, N = 3; cout << MaxExpect(M, N); return 0; }
Output
If we run the above code we will get the following output −
1.875
To Continue Learning Please Login
Login with Google