C Exercise Example 21
100 cases of classic C language
Title: Monkey eating peach issues: the monkey off his first day of a number of peach, half eaten immediately, not addiction, but also eat a morning in turn eaten by the remaining peach half, then eat a . After the morning ate the day before the rest of the half a zero. Day 10 in the morning when you want to eat, see only one peach. Seeking first day of the total number picked.
Program analysis: take the method of reverse thinking, inferred from the forward.
1) Let x1 is the number of the previous day peaches, peaches for the next day set x2 number, then:
x2 = x1 / 2-1, x1 = (x2 + 1) * 2
x3 = x2 / 2-1, x2 = (x3 + 1) * 2
So: x = before (after x +1) * 2
2) From day 10 to day 1, by analogy, it is a cyclic process.
Source Code:
// Created by www.w3big.com on 15/11/9. // Copyright © 2015年 本教程. 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; // 第一天的桃子数是第2天桃子数加1后的2倍 x2=x1; day--; } printf("总数为 %d\n",x1); return 0; }
The above example output is:
总数为 1534