Okay, I have a problem that goes something like this: I have a union of road stripe painters where each painter will only paint a section of 2 miles on the road and charge $200 for the service. If the road is longer than 2 miles, the painter will divide it into three equal parts, charge $100, and subcontract each road to three different painters. Each of the hire will do the same thing where if the road is longer than 2 miles, each of the painters will subcontract another 3 and so on and so on. So the diagram would look something like a k-ary tree. What I have to find is the total cost it takes to paint a certain amount of road length. To illustrate, given an arbritary length of 7 miles the result would be something like:
7 = $100
2.6, 2.6, 2.6 = 3 x $100 = $300
.96, .96, .96, .96, .96, .96, .96, .96, .96 = 9 x $200 = 1800
Total cost - $2200
The code I have so far for a function that calculates the total cost is:
- int costofpainting(double length, int power)
-
{
-
double multiplier(0.0);
-
int answer, i;
-
-
multiplier = 1.0;
-
if(length > 2.0)
-
{
-
for(i = 0; i < power; i++)
-
multiplier = multiplier * 3.0;
-
-
answer = (multiplier * 100) + costofpainting(length/3.0, power + 1);
-
}
-
else if(length <= 0.0)
-
return -1;
-
else if(length <= 2.0)
-
{
-
for(i = 0; i < power; i++)
-
multiplier = multiplier * 3.0;
-
-
return (multiplier * 200);
-
}
-
}
I used a simple driver to test it:
- int main()
-
{
-
int num;
-
num = costofpainting(7.0, 0);
-
-
cout << num << '\n';
-
-
}
However, the ending results prints out 80320 which is incorrect. The actual prototype given for the costofpainting function is "int costofpainting(double length);" But no matter how hard I try I couldnt figure out a formula that would work to compute the cost unless I have an additional variable passed in, hence int power. That way, with each division of the number entered, power will be increased to indicate how many sets of three painters are hired with each subcontracting. As far as tracing the algorithm that I wrote, it seems fine, unless I'm doing something wrong. Anyone can clarify or help me figure out how to do it by using the function prototype given?
Regards,
Jthep