Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 21

C Exercise 21

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** The monkey and peaches problem: A monkey picks some peaches on the first day, immediately eats half of them, and still not satisfied, eats one more. The next morning he eats half of the remaining peaches and one more. Every morning after that he eats half of what remained from the previous day plus one. On the morning of the 10th day, when he wants to eat again, only one peach is left. How many peaches did he pick on the first day?

**Analysis:** Use reverse thinking and infer from the end back to the beginning.

  1. Let x1 be the number of peaches the previous day and x2 the number the next day, then:

x2=x1/2-1, x1=(x2+1)*2

x3=x2/2-1, x2=(x3+1)*2

And so on: x_prev = (x_next + 1) * 2

  1. From day 10 you can work back to day 1, which is an iterative process.

Program source code:

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. 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 twice (the number on the second day plus 1)

x2

=

x1

;

day

--;

}

printf

(

"

The total is %d

\

n

"

,

x1

)

;

return

0

;

}

The output of the above example is:



总数为 1534

100 Classic C Language Examples 100 Classic C Language Examples