Interesting algorithms for monkeys to eat peach

Source: Internet
Author: User
On the first day, the monkey picked up a few peaches and immediately ate half of them. In the morning of the next day, I ate half of the remaining peaches and one more. In the future, I eat the remaining half of the previous day every morning. When you want to eat again in the morning of the seventh day, there is only one peach left. How many peaches can be picked on the first day. This question adopts the reverse push method, so pay attention to the condition of the end of the loop. In most cases, we use the increment method of loop. in this question, we use the decrease method, so it is I1.

On the first day, the monkey picked up a few peaches and immediately ate half of them. In the morning of the next day, I ate half of the remaining peaches and one more. In the future, I eat the remaining half of the previous day every morning. When you want to eat again in the morning of the seventh day, there is only one peach left. How many peaches can be picked on the first day.

C program:

#include 
 
   int main(){int sum = 1, i;int wait;for (i = 9; i >= 1; i--){sum = (sum + 1) * 2;}printf("the num of peace are %dn", sum);scanf_s("%d", &wait);return 0;}
 

This question adopts the reverse push method, so pay attention to the condition of the end of the loop. In most cases, we use the increment method in the loop mode. therefore, I> = 1. Step-by-step verification is as follows:

#include 
 
  int main(){    int prev ;    int next = 1 ;    int i;int wait;    for (i = 9; i >= 1; i--)    {        prev = (next + 1) * 2 ;        printf("i=%d total=%-5d n", i, prev);        next = prev;    }scanf_s("%d,&wait");    return 0;}
 

Program running result:

i=9 total=4i=8 total=10i=7 total=22i=6 total=46i=5 total=94i=4 total=190i=3 total=382i=2 total=766i=1 total=1534

This article is available at http://www.nowamagic.net/librarys/veda/detail/612.

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.