C language programming example (3): Monkey peach eating problem, C language programming

Source: Internet
Author: User

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;}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.