4
public class Fibonacci {
    public static long fib(int n) {
        if (n <= 1) return n;
        else return fib(n-1) + fib(n-2);
    }

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        for (int i = 1; i <= N; i++)
            System.out.println(i + ": " + fib(i));
    }
}

假设用户输入“java Fibonacci 7”,结果将是这样的:

1:1
2:1
3:2
4:3
5:5
6:8
7:13

我似乎对它的工作原理完全感到困惑,从参数 3 开始。当 fib(i) 方法通过 3 时,它不应该也返回 3,因为如果 n = 3 那么 fib(n-1) 的总和/ n-1 是 2 / 并且 fib(n-2) / n-2 是 1 / 是 3。以此类推其他数字向前。

4

20 回答 20

15

这是一个更简单的代码来生成像'0 1 1 2 3 ...'这样的斐波那契数列。

public static void main (String[] args) {
    int f = 0;
    int g = 1;

    for (int i = 1; i <= 10; i++) {
        System.out.print(f + " ");
        f = f + g;
        g = f - g;
    } 

    System.out.println();
}
于 2013-09-27T07:40:07.970 回答
4

如果您将 3 传递给您的函数,它将执行以下操作:

fib(3) = fib(2) + fib(1) //so we we are into the else statement, because 3 > 1
= fib(2) + 1             //fib(1) = 1 because 1 <= 1 so you return it (if statement)
= (fib(1) + fib(0)) + 1  //2 > 1 => we go to the else statement
= (1 + 0) + 1            //0 <= 1 & 1 <= 1 so we are into the if and return the values 
= 2
于 2013-09-27T07:36:12.323 回答
2
                           F(n)
                            /    \
                        F(n-1)   F(n-2)
                        /   \     /      \
                    F(n-2) F(n-3) F(n-3)  F(n-4)
                   /    \
                 F(n-3) F(n-4)

请注意,许多计算是重复的!需要注意的重要一点是该算法是指数的,因为它不存储先前计算的数字的结果。例如,F(n-3) 被调用了 3 次。

有关更多详细信息,请参阅 dasgupta 第 0.2 章的算法

于 2014-03-04T07:21:38.323 回答
2
public static int f(int n){
    if (n <= 1) {
        return n;
    } else {
        return f(n - 1) + f(n - 2);
    }
}

public static void main(String[] args){
    Integer c = 4;
    Integer answer = f(c);
    System.out.println("Fibonacci " + c + "'s number is: " + answer);
}
于 2014-08-04T10:14:52.787 回答
2

我使用 Java 8 Stream 的解决方案:

public class Main {
    public static void main(String[] args) {
        final int n = 7;
        Fibonacci fibonacci = new Fibonacci();
        Stream.generate(fibonacci::next)
                .limit(n)
                .forEach(System.out::println);
    }
}

public class Fibonacci {
    private long next = 1;
    private long current = 1;
    private int count = 1;

    public FibonacciNumber next() {
        FibonacciNumber fibonacciNumber = new FibonacciNumber(count++, current);
        long previous = current;
        current = next;
        next = current + previous;
        return fibonacciNumber;
    }
}

public class FibonacciNumber {
    private final int count;
    private final long value;

    public FibonacciNumber(int count, long value) {
        this.count = count;
        this.value = value;
    }

    @Override
    public String toString() {
        return count + ": " + value;
    }
}
于 2017-07-14T21:42:10.117 回答
1

我认为您将斐波那契数列中的索引 (n) 与该索引处的实际值混淆了。fib(n=3) = fib(n-1=2) + fib(n-2=1) = 1 + 1 = 2

于 2013-09-27T07:34:08.833 回答
1

你为什么不试试这个简单的代码。就像我们在没有递归的斐波那契中所做的一样。

public class FinnonnacciDemo2 {

    static int no = 0, n = 8;

    public static void main(String[] args) {
        // This will print series till 8
        fib(0, 1);
    }

    public static void fib(int a, int b) {
        // Terminating condition.
        if (a >= n) {
            return;
        }

        else {
            System.out.print("\t" + no);
            no = a + b;
            a = b;
            b = no;
            fib(a, b);
        }
    }
} 
于 2013-09-27T07:35:06.487 回答
1

您可以分两行完成!

执行此操作的最短输入(尽管不是最有效的):

    int fib( int x ) {
        return x > 1 ? fib(x - 1) + fib(x - 2) : x; }

如果你想要一个快速的算法,试试这个:

        ///fast version fibbonacci sequence.
        public static float fibonacci(int x){
           float[] sequence = new float[x];
           sequence[0] = 1;
           sequence[1] = 1;
          if (x > 1){
             for (int i = 2; i < x; i++){
               sequence[i] = sequence[i-1] + sequence[i-2];
             }
          }
          for (float z : sequence){
              System.out.print("{ " + z + "}, ");
          }
          return sequence[x-1];
        }
于 2016-02-08T23:23:12.950 回答
0

斐波那契数列要么从零开始,要么从 1 开始,其中没有一个选项将 3 作为第三个数字。

1 1 2 3 5 ...

0 1 1 2 3 5 8 ...

通常的方法是使用第二个选项,但从索引 0 开始,以便 fib(0) = 0,fib(1) = fib(2) = 1,例如此处所述:http: //oeis.org/A000045

于 2013-09-27T07:36:15.563 回答
0

是递归方法...fib(3)=fib(3-1)+fib(3-2)= fib(2)+fib(1)=(fib(2-1)+fib(1-1))+fib(1)= fib(1)+fib(0)+fib(1)= 1 + 0 + 1

于 2013-09-27T07:38:24.690 回答
0

斐波那契数是前两个连续数的计算总和。它以 0 1 1 2 3 5 8... 开头,以此类推。所以它就像——

fib(3) = fib(2) + fib(1)
       = fib(1) + fib(0) + 1 //fib(1) = 1
       = 1 + 0 + 1 //fib(0) = 0
       = 2

递归方法效率较低,因为它涉及使用堆栈的函数调用,如果函数被频繁调用以计算更大的斐波那契数,也有可能发生堆栈溢出。

于 2013-09-27T07:44:13.113 回答
0
import java.math.BigDecimal;

public abstract class Fibonacci {

    public static void main(String[] args) {
        Integer max = Integer.valueOf(args[0]);
        BigDecimal[] fibs = { new BigDecimal(0), new BigDecimal(1) };
        BigDecimal current;
        System.out.print("1 ");
        for (int i = 0; i < max + 1; i++) {
            current = fibs[1].add(fibs[0]);
            System.out.print(current + " ");
            fibs[0] = fibs[1];
            fibs[1] = current;
        }
    }
}
于 2017-03-07T05:28:46.547 回答
0

下面的方法返回索引 n 处的斐波那契数。

 public static long getFibonacci(int n) {
            List<Long> fibonacciNumbers = new ArrayList();
            long j = 0;
            int k = 0;
            for (int i = 0; i <= n; i++) {
                System.out.println("i = " + i);
                if (i == 2) {
                    j += (i - 2);
                } else if (i > 2) {
                    j = fibonacciNumbers.get(i - 1) + fibonacciNumbers.get(k - 2);
                } else {
                    j += i;
                }
                fibonacciNumbers.add(j);
                k++;
                System.out.println("Fibonacci Array = " + Arrays.toString(fibonacciNumbers.toArray()));
            }
            return fibonacciNumbers.get(fibonacciNumbers.size() - 1);
        } 
于 2018-03-06T17:53:56.457 回答
0

为什么不使用下一个公式:

private static int fibonacci(int n) {
    if (n == 1) {
        return 1;
    } else if (n == 2) {
        return 1;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}
于 2018-03-09T20:02:56.267 回答
0

这是我使用 BigInteger 的动态编程实现。

   import java.math.BigInteger;
   import java.util.HashMap;
   import java.util.Map;
   import java.util.Scanner;

/**
 * Topic: Dynamic Programming
 * Algorithm: Fib Algorithm Implementation
 *
 * Author: Chris M. Perez Santiago
 * Date: 4 / 15 / 2018
 **/


  public class Main {
     private static BigInteger[] b = new BigInteger[100000001];
     private static Scanner console = new Scanner(System.in);

  public static void main(String[] args) {
     long n = console.nextLong();
     for(long i=1;i<=n;i++) System.out.println(initFib(i));
  }

  private static BigInteger dpFib(Map<Long , BigInteger> map , long n){
     if(map.containsKey(n)) return map.get(n);

     map.put(n - 1 , dpFib(map , n - 1));
     map.put(n - 2 , dpFib(map , n - 2));
     BigInteger sum = map.get(n - 1).add(map.get(n - 2));
     map.put(n , sum);
     return sum;
  }

  private static BigInteger initFib(long n){
     if(BigInteger.valueOf(n).equals(BigInteger.ONE) || BigInteger.valueOf(n).equals(BigInteger.ZERO))
       return BigInteger.ONE;
     Map<Long , BigInteger> map = new HashMap<>();
     map.put(1L , BigInteger.ONE);
     map.put(2L , BigInteger.ONE);
     return dpFib(map , n);
  }
}
于 2018-06-05T17:42:38.293 回答
0
import java.util.Scanner;
public class Fibonacci {
    public static void main(String[] args) {
        Scanner scn = new Scanner(System. in );
        System.out.println("Enter a number upto which fibonacci numbers should be displayed");
        int fib = scn.nextInt();
        int a = 0,
        b = 1,
        res = 0;
        System.out.print(a + " " + b + " ");
        while (res <= fib) {
            res = a + b;
            a = b;
            b = res;
            if (res > fib) break;
            System.out.print(res + " ");
        }
    }
}
于 2019-12-07T09:55:50.390 回答
0

1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89

public void fibonacci(){
    int n1 = 0;
    int n2 = 1;
    int n3;
    int count = 10;
    Log.d("DBG",n1 + " , " + n2);
    for (int i = 1; i <= count ; i++) {
        n3 = n1 + n2;
        Log.d("DBG",i + "= " + n3+"");
        n1 = n2;
        n2 = n3;
    }
}
于 2020-09-09T04:20:59.930 回答
0
package Loops;
import java.util.Scanner;
public class FibonacciClass {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.println("Enter the number upto which you want to generate Fibonacci series");
        int x= sc.nextInt();
        int [] testing= new int[x];
        int first_Value=0;
        int second_value=1;
        int third_value=0;
        System.out.println(first_Value);
        for(int i=1;i<testing.length;i++){
            first_Value=second_value;
            second_value=third_value;
            third_value=first_Value+second_value;
            System.out.println(third_value);
            }
        }
        }
于 2021-08-27T23:33:55.917 回答
0
// using recurrsion
static void fibonacci_recurrsion2(int count, int first, int second) {
    while (count > 0) {
        int temp = second;
        if (first == 0) {
            System.out.print(first);
        }
        System.out.print("," + second);

        second = first + second;// fib(first, second);
        first = temp;
        fibonacci_recurrsion(count - 1, first, second);
    }
}

或者

static void fibonacci_recurrsion(int count, int first, int second) {
        if (count >= 0) {
            System.out.print(first + ",");
            first = first + second;// fib(first, second);
            second = first - second;// fib(first, second);
            fibonacci_recurrsion(count - 1, first, second);
        }
    }
于 2021-09-13T03:51:50.960 回答
-2
import java.util.Scanner;

public class Fibonacci2 {

    public static void main(String[]args){

        int a;
        try (Scanner sc = new Scanner(System.in)) {
            System.out.print("Number of Fibonacci numbers to print: ");
            a = sc.nextInt();
            sc.close();
        }
        int c=1; /*c current number b last number*/
        int b=0;
        System.out.println(b);
        System.out.println(c);
        int bb;
        for (int z = 2; z < a ; z++){
        bb = b; 
        b = c;
        c = bb + b; /*bb last last number*/
        System.out.println(z);

    }
    }
}
于 2014-12-06T12:03:31.823 回答