C language programming example (3): Monkey peach eating problem, C language programming
From: http://www.jb51.net/article/38051.htm
Http://blog.csdn.net/Neil_Wesley/article/details/51484026
Question: monkeys eat peaches. On the first day, the monkeys picked up several peaches and immediately ate half of them.
In the morning of the next day, I ate half of the remaining peaches and one more. Later, I eat the rest of the day every morning.
Half and zero. When you want to eat again in the morning of the seventh day, there is only one peach left. Calculate the total number of extracted items on the first day.
Train of Thought Analysis:
Use
Reverse ThinkingFrom the back to the front, we can infer that there is the same place, that is, the recursive formula appears, and the recursive method can be used.
So that S10 = 1, it is easy to see S9 = 2 (S10 + 1), simplify it
S9 = 2S10 + 2
S8 = 2S9 + 2
.....
Sn = 2Sn + 1 + 2
Next I will solve this problem. (The first is the normal loop mode, and the second is the recursion Mode)
Method 1: while
#include<stdio.h>int main(){ int day,x1,x2; day=9; x2=1; while(day>0) { x1=(x2+1)*2; x2=x1; day--; } printf("the total is %d\n",x1);}
Method 2: Recursion
#include<stdio.h>int sumPeach(int day);int main(){ int sum; sum=sumPeach(1); printf("%d",sum);}int sumPeach(int day){ if(day==10) { return 1; } else return 2*sumPeach(day+1)+2;}