C Exercise Example 21
Question: The Monkey and the Peaches: On the first day, a monkey picked several peaches and ate half of them immediately. Not satisfied, it ate one more. On the second morning, it ate half of the remaining peaches plus one more. This pattern continued every morning, eating half of the remaining peaches plus one more. By the morning of the 10th day, it found there was only one peach left. How many peaches did the monkey pick on the first day?
Program Analysis: Use reverse thinking, working backwards from the end.
1) Let x1 be the number of peaches the previous day, and x2 be the number of peaches the second day, then:
x2 = x1/2 - 1, x1 = (x2 + 1) * 2
x3 = x2/2 - 1, x2 = (x3 + 1) * 2
And so on: x_previous = (x_next + 1) * 2
2) From the 10th day, we can work backwards to the 1st day, which is a cyclic process.
Source Code:
// Created by www.tutorialpro.org on 15/11/9.
// Copyright © 2015 tutorialpro.org. 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 number of peaches on the first day is 2 times the number of peaches on the second day plus 1
x2 = x1;
day--;
}
printf("The total number is %d\n", x1);
return 0;
}
The output of the above example is:
The total number is 1534