Home  >  Article  >  Java  >  Example of implementation of monkey eating peach problem algorithm in Java

Example of implementation of monkey eating peach problem algorithm in Java

黄舟
黄舟Original
2017-10-18 10:24:191871browse

This article mainly introduces the monkey eating peach problem algorithm implemented in Java. It briefly describes the monkey eating peach problem and provides specific implementation techniques for solving the monkey eating peach problem in Java in the form of examples. Friends who need it can refer to it

The example in this article describes the monkey eating peach problem algorithm implemented in Java. I share it with you for your reference. The details are as follows:

Monkey eating peach problem

Overview: The monkey picked N peaches on the first day and ate half of them at that time. Still not satisfied, I ate another peach; the next day I ate half of the remaining peaches and ate one more; from now on, I ate half and one of the peach from the previous day every day, and I didn’t think about it until the nth day When we ate, there was only one peach left. How many peaches were picked on the first day?

Ideas and calculation steps (function expression to find how many peaches were picked in total):

The number of days from now is used as a variable

f(1) = 1 (remaining Number of peaches)
f(2) = f(3) - (ate some) = f(3) -(f(3)/2+1) = f(3)/2-1
....
f(n) = f(n+1)/2-1(recursive formula)

So we can get the recursive formula:

f(n -1) = f(n)/2-1 => 2f(n-1) = f(n) - 2 => f(n)=2f(n-1) +2 (This is what we want The formula)

Then you can find out the total number of peaches picked by the monkey at any number of days from now!

For example, f(10) means 10 days from now (the number of peaches owned by the monkey 10 days ago)!

The specific code is given below:


package javastudy;
import java.util.Scanner;
public abstract class Testit2 {
  // 猴子吃桃问题
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n;
    n = in.nextInt();
    System.out.println(f(n));
    in.close();
  }
  static int f(int n) {
    if (n == 1)   //离现在只有一天的时候那就只剩下一个!
    return 1;
    return 2 * f(n - 1) + 2;
  }
}

The above is the detailed content of Example of implementation of monkey eating peach problem algorithm in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn