C++ Problem A: Number of parent/grand parents/great granparents/great great... U
ID: 3683751 • Letter: C
Question
C++
Problem A: Number of parent/grand parents/great granparents/great great...
Use recursionto find how many ancestors you have up to a certain number of generations back. For
example, 1 generation back is how many parents people have on average. 2 generations back
correspond to the average number of grand parents.For our purpose, a child of a “single parents” have only one parent. A child with a parent that divorced
but then remarried will have 3 parents (2 biological and one step). All other children will have two parents. Assume about 1/3 of children have a single parent,
and 2/9 have 3 parents. Ask the user how many generations back you want to look. Then simulate the number of parents based
on the probabilities above a million times to find the average. The computer will take a bit of time to
think for these problems, so it is advised that you only test on small numbers on slower machines.
Hint: you might want to use a double to help find the average.
Example 1 (
user input is underlined
):
How many generations back?
1
There are approximately 1.88881 people 1 generations back on average
Example 2 (
user input is underlined
):
How many generations back?
0
There are approximately 1 people 0 generations back on average
Example 3 (
user input is underlined
):
How many generations back?
2
There are approximately 3.56909 people 2 generations back on average
Example 4 (
user input is underlined
):
How many generations back?
6
There are approximately 45.4591 people 6 generations back on average
Explanation / Answer
#include <iostream>
#include <cstring>
using namespace std;
double find(int n)
{
if(n==0)
return 1;
return (1.0/3)*find(n-1) + (2.0/9)*find(n-1)*3 + (4.0/9)*find(n-1)*2;
}
int main()
{
int n;
cout<<"How many generations back? ";
cin>>n;
cout<<"There are approximately "<<find(n)<<" people "<<n<<" generations back on average ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.