C Exercise Example 21
Title:Monkey peach-eating problem: On the first day, the monkey picked a number of peaches, ate half of them immediately, but was not satisfied, so it ate one more. The next morning, it ate half of the remaining peaches and one more. From then on, every morning it ate half of what was left from the previous day plus one. On the morning of the 10th day, when it wanted to eat again, it saw only one peach left. Find how many peaches it picked in total on the first day.
Program analysis:Adopt a reverse-thinking approach and infer from back to front.
1) Let x1 be the number of peaches on the previous day, and x2 be the number of peaches on the next day, then:
x2=x1/2-1, x1=(x2+1)*2
x3=x2/2-1, x2=(x3+1)*2
By analogy: x_prev = (x_next + 1) * 2
2) From day 10, it can be inferred back to day 1; this is a loop process.
Program source code:
Example
The output of the above example is:
总数为 1534other extensions