将python fibonacci代码转换为java?

时间:2016-02-14 21:45:25

标签: java python fibonacci

所以这是python代码:

def fib(n):
  ## Handle special case when n == 0
  if n == 0:
    return 0
  ## General case, return the first of the
  ## two values returned by fibaux
  else:
    return fibaux(n)[0]

## Auxiliary function
## Return the nth and (n-1)th Fibonacci numbers
## n must be an integer >= 1
def fibaux(n):
  ## Base case of for recursion
  if n == 1:
    return 1, 0
  else:
    ## Recursive case
    f2, f1 = fibaux(n - 1) ## **this is the part I cant figure out in java**
    return f2 + f1, f2

代码的**部分(f2,f1 = fibaux(n - 1))在我的java代码中不正确。这是java代码:

public static int[] fib(int number){
  if (number == 0){
     return new int[] {0};
  }
  else{
     int fibauxArray[] = fibaux(number);
     int f3 = fibauxArray[0];
     return new int[] {f3};
  }
}

public static int[] fibaux(int number){
  if (number == 1){
     return new int[] {1, 0};
  }
  else{
     int[] Q = fibaux(number-1);
     int[] R = fibaux(number-1);
     int f2 = Q[0] + R[0];
     int f1 = Q[0];

     return new int[] {f2, f1};
 }

在python中,f2和f1是不同的值,但在我的java代码中,Q []和R []是相同的值,所以它不能计算出正确的结果。我不明白如何使这个工作?谢谢!

3 个答案:

答案 0 :(得分:4)

尝试:

public static int fib(int number){
  if (number == 0){
     return 0;
  }
  else{
     int fibauxArray[] = fibaux(number);
     return fibauxArray[0];
  }
}

public static int[] fibaux(int number){
  if (number == 1){
     return new int[] {1, 0};
  }
  else{
     int[] Q = fibaux(number-1);
     int f2 = Q[0];
     int f1 = Q[1];

     return new int[] {f2+f1, f2};
 }
}

答案 1 :(得分:0)

使用Pair类:

class Pair {
    private int first;
    private int second;
    // getters, setters, constructor
}

这部分:

def fib(n):
  ## Handle special case when n == 0
  if n == 0:
    return 0
  ## General case, return the first of the
  ## two values returned by fibaux
  else:
    return fibaux(n)[0]

可以"翻译"到:

int fib(int n) {
  // Handle special case when n == 0
  if (n == 0) {
    return 0;
  }
  // General case, return the first of the
  // two values returned by fibaux
  else {
    return fibaux(n).getFirst();
  }
}

这一部分:

## Auxiliary function
## Return the nth and (n-1)th Fibonacci numbers
## n must be an integer >= 1
def fibaux(n):
  ## Base case of for recursion
  if n == 1:
    return 1, 0
  else:
    ## Recursive case
    f2, f1 = fibaux(n - 1) ## **this is the part I cant figure out in java**
    return f2 + f1, f2

为:

// Auxiliary function
// Return the nth and (n-1)th Fibonacci numbers
// n must be an integer >= 1
Pair fibaux(int n):
  // Base case of for recursion
  if (n == 1) {
    return new Pair(1, 0);
  } else {
    // Recursive case
    Pair next = fibaux(n - 1);
    return new Pair(next.getFirst() + next.getSecond(), next.getFirst());
  }
}

Demo

答案 2 :(得分:0)

fibaux返回索引0中的数组元素n和索引1中的n-1。

不要执行两次fibaux。只需使用第一次执行的结果。

所以你应该这样做..

else{
int[] Q = fibaux(number-1);
int f2 = Q[1] + Q[0];
int f1 = Q[0];
return new int[] {f2, f1};