C Exercise Example 21

100 Classic C Examples

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

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. // #include <stdio.h> #include <stdlib.h> int main(){ int day, x1 = 0, x2; day=9; x2=1; while(day>0) { x1=(x2+1)*2; // The first day's peach count is twice (the second day's peach count plus 1) x2=x1; day--; } printf("Total is %d\n",x1); return 0; }

The output of the above example is:

总数为 1534

100 Classic C Examples

other extensions