Problem : There are a bunch of peaches, the first day of the monkeys ate half of them, and eat one. After the monkeys eat half of it every day, then eat a, when the first 10 days, and found that only a peach. Question: How many peaches initial total.
Analysis of ideas :
- Day 10 only a peach;
- 9th day = number of peaches (peach day 10 the number of + 1) *;
- Law: n-number of days Peach: peach (n) = (peach (n + 1) + 1) * 2
code show as below:
package main
import "fmt"
func peach(n int) int{
if n>10 || n<1 {
fmt.Println("输入的天数不对")
return 0
} else if n==10 {
return 1
} else {
return (peach(n+1)+1)*2
}
}
func main() {
fmt.Print("请输入天数:")
var n int
fmt.Scan(&n)
fmt.Printf("第%v天桃子的数量是:%v",n,peach(n))
}
Execution results as shown below: