Example of monkey eating peach algorithm implemented in Java
This paper describes the algorithm of monkey eating peach problem implemented in Java. Share with you for your reference, as follows:
Monkey eating peach problem
Overview: the monkey picked n peaches on the first day. At that time, he ate half of them. If he was not satisfied, he ate another one; The next day he ate half of the remaining peaches and another one; After that, I will eat half and a half of the previous day's body every day. When I want to eat on the n day, there will be only one peach left. How many peaches did I pick on the first day?
Train of thought and calculation steps (find the function expression of how many peaches to pick):
The number of days from now is used as a variable
F (1) = 1 (number of peaches left) f (2) = f (3) - (ate some) = f (3) - (f (3) / 2 + 1) = f (3) / 2-1 F (n) = f (n + 1) / 2-1 (recurrence formula)
Therefore, the recurrence formula can be obtained:
F (n-1) = f (n) / 2-1 = > 2F (n-1) = f (n) - 2 = > F (n) = 2F (n-1) + 2 (this is the formula we want)
Then you can find the peaches picked by the monkeys any day from now!
For example, f (10) means 10 days from now (the number of peaches owned by monkeys 10 days ago)!
Specific codes are given below:
For more information about Java algorithms, readers who are interested can see the topics on this site: Java data structure and algorithm tutorial, summary of Java DOM node operation skills, summary of java file and directory operation skills, and summary of Java cache operation skills