【问题标题】:printing the results of a fibonacci series打印斐波那契数列的结果
【发布时间】:2013-09-01 21:53:51
【问题描述】:

我知道斐波那契数列的编码是:

int fib(int n)
{
    if (n==0 || n==1) return n;
    else return fib(n-1)+fib(n-2);
}

我想知道是否有办法使用上述代码打印系列的先前结果,但既不使用 void 函数(仅充当系列的打印机)也不为每个调用斐波那契函数计算

我不想这样做

for (int i=0;i<4;i++){
     System.out.prinntln(fib(i));
}

我只想调用一次函数,如下所示:

fib(4);

并且打印是:

0,1,1,2,3

当然使用递归

有什么想法吗? 谢谢

【问题讨论】:

    标签: java fibonacci


    【解决方案1】:
    package Practice;
    
    public class Fabonacci {
    
        public static void main(String[] args) 
        {
            int a,b,c;
            a=0;
            b=1;
            c=2;
    
            for(int i=1; i<=10; i++)
            {
                c=a+b;
                System.out.println(a);
                a=b;
                b=c;        
            }
        }
    }
    

    这将输出为:

    0 1 1 2 3 5 8 13 21 34
    

    【讨论】:

    • 这将输出为
    • 0 1 1 2 3 5 8 13 21 34
    【解决方案2】:

    好的,所以我没有看到你想保留递归。

    那么这个怎么样:

    public class fib {
    
      static int fibonacci(int value, boolean printThis) {
        int result;
        if (value==0 || value==1) {
          result = value;
          if (printThis) {
            System.out.print(result);
            System.out.print(", ");
          }
        } else {
          if (printThis) {
            result =  fibonacci(value-1, true)+fibonacci(value-2, false);
            System.out.print(result);
            System.out.print(", ");
          } else {
            result = fibonacci(value-1, false)+fibonacci(value-2, false);
          }
        }
        return result;
      }
    
      public static void main(String []args) {
        fibonacci(7, true);
        System.out.println();
      }
    }
    

    如果没有布尔值printThis,我认为您无法控制仅打印由两个值的递归生成的树的一条路径。为了更清楚地说明这一点,请查看如何递归地为教职员工执行此操作。

    递归调用反向计算,所以faculty(n)faculty(n-1) 之前被调用。由于要在faculty(n) 之前打印faculty(n-1) 的值,因此需要在返回值之前打印,如下所示:

    static int faculty(int v) {
      int result;
      if (v==0) {
        result = 1;
      } else {
        result = v*faculty(v-1);
      }
      System.out.print(result);
      System.out.print(", ");
      return result;
    }
    

    这将为您提供升序的值。我希望你能原谅最后一个逗号,如果你想在没有布尔参数控制它的情况下摆脱它,你需要定义一个额外的函数。

    因此,您可以看到无需布尔值来控制打印的教职员工。

    但这是因为faculty 不会跨越递归调用树,而只是一个调用序列。如前所述,我只看到如果你有一个完整的调用树,你可以通过添加一个布尔函数来控制打印。

    这就是你所追求的吗?

    无论如何,这仍然是我的第一个答案(效率更高,并且会更快地为您提供相同的输出):

    以迭代方式而不是递归方式计算斐波那契数。

    最简单的方法是使用数组 fib[]。 初始化为 fib[0] = 0,fib[1] = 1。 然后迭代 i = 2 到 n,其中 fib[i] = fib[i-1] + fib [i-2]。

    调整它也很容易,因此您不需要完整的数组,而只需要存储两个变量 fib[i-1], fib[i-2].

    事实上,您可以采用这个迭代循环,然后再次使其成为递归循环,但它的结构与您原来的斐波那契函数不同。

    【讨论】:

    • 谢谢,但正如我在帖子中提到的,我真的很想用递归来使用它
    • @MrM.:好的,所以我尝试递归地执行此操作。请参阅上面的编辑。
    • @MrM:你试过我的代码了吗?在我的机器上工作 8^) 这是您正在寻找的答案,还是缺少什​​么?
    【解决方案3】:

    一行写出斐波那契数列。

       public class Fib {
            public static void main(String[] args) {
                for(int i=1,f=0,n=0; n<15; n++,System.out.println(i=(f+(f+i))-(f=f+i)));            
            }
        }
    

    【讨论】:

      【解决方案4】:

      这是一个打印每个计算的简单示例:

      int x = 1;
      int a = 0;
      int t;
      
      while(true)
      {
          System.out.println(x);
      
          t = x;
          x = x + a;
          a = t;
      
          if (x > 30)
          {
              break;
          }        
      }
      

      这将打印以下内容:

      1
      1
      2
      3
      5
      8
      13
      21
      

      这是小于 30 的斐波那契数列。

      【讨论】:

      • 感谢 Michael 编辑我的文本,但在 java 中它可以在变量之间有或没有空格
      【解决方案5】:

      您可以编写另一个方法void printFib(int n),然后使用循环打印此方法中的每个fib(n)。返回值的方法实际上不应该打印任何内容。但是如果你像 Zane 所说的那样迭代地计算每个数字,你可以有一个 void 方法来计算和打印这些值。我看不到任何方法可以在递归斐波那契方法中打印值。

      【讨论】:

        【解决方案6】:

        斐波那契数列的一个简单例子。

        class Fibonacci {
        public static void main(String args[]) {
        
            fibonacciSeries(6);
        
        }
        
        static void fibonacciSeries(int num) {
            int a = 0, b = 1, i, c;
        
            for (i = 0; i <= num; i++) {
                if (i <= 1) {
                    c = i;
                } else {
                    c = a + b;
                    a = b;
                    b = c;
                }
                System.out.print(c);
                if(i != num) {
                    System.out.print(",");
                }
            }
        }
        

        输出:

        0,1,1,2,3,5,8

        【讨论】:

          【解决方案7】:

          我希望它是打印斐波那契数列的简单方法

          斐波那契数列

          public class Fib
          {
          public static void main(String[] args)
          {
          int first=0,second=1;next;
          System.out.prinf("%d %d ",first,second);
              for(int i=0;i<=10;i++)
              {
               next=first+second;
               first=second;
               second=next;
               System.out.printf("%d ",second);
                 }
             }
          }
          

          输出

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

          【讨论】:

          • 欢迎来到 StackOverflow。请说明您的答案与已发布的答案有何不同或更好。
          • 我在程序中使用了 next,first 和 second 作为变量。它很容易理解程序的工作原理,特别适合新程序员。这就是为什么我认为这段代码与其他代码不同。
          【解决方案8】:

          这可能是一个不错的...

           public static void febonassi(int range, int pre, int nxt) {
              System.out.println(pre);
              if (nxt <= range)
                  febonassi(range, nxt, nxt + pre);
          }
          

          【讨论】:

            【解决方案9】:

            我使用了大小为 howManyDigit 的 int 数组。

            这是我可以使用较少变量编写斐波那契数列的最佳方式

                int[] array = new int[howManyDigit];
                for(int i=0;i<howManyDigit;i++){
                    if(i>1)
                         array [i]=array [i-1]+array [i-2];
                    else
                        array [i]=i;
                }
                System.out.println(Arrays.toString(array));
            

            【讨论】:

            • How to write an answer。添加更多详细信息以证明您的回答是正确的。
            • 您必须在答案部分通过单击编辑来执行此操作,因为某些 cmets 在否时会被隐藏,所以 cmets 的可见性受到限制。 cmets 的增长。
            【解决方案10】:

            到目前为止,这是我为斐波那契数列得出的最有效和最快的方法:

            斐波那契动态版

            public static BigInteger getFibonacciDynamic(long n) {
            
                BigInteger[] fibonacci = new BigInteger[(int) n + (n == 0 ? 2 : 1)];
                fibonacci[0] = BigInteger.valueOf(0);
                fibonacci[1] = BigInteger.valueOf(1);
            
                for (int i = 2; i <= n; i++) {
                    fibonacci[i] = fibonacci[i - 1].add(fibonacci[i - 2]);
                }
            
                return fibonacci[(int) n];
            }
            

            对于前 1000 个值,您可以这样运行它:

            public static void main(String[] args) {
            
                int index = 0;
                while (index < 1000) {
                    long time = System.currentTimeMillis();
                    BigInteger value = getFibonacciDynamic(index);
                    System.out.println("VALUE: " + value + " TOOK: " + (System.currentTimeMillis() - time) + "ms" + " OF INDEX: " + index);
                    index++;
                }
            }
            

            并且会打印出来:

            VALUE: 0 TOOK: 0ms OF INDEX: 0
            VALUE: 1 TOOK: 0ms OF INDEX: 1
            VALUE: 1 TOOK: 0ms OF INDEX: 2
            VALUE: 2 TOOK: 0ms OF INDEX: 3
            VALUE: 3 TOOK: 0ms OF INDEX: 4
            VALUE: 5 TOOK: 0ms OF INDEX: 5
            VALUE: 8 TOOK: 0ms OF INDEX: 6
            VALUE: 13 TOOK: 0ms OF INDEX: 7
            VALUE: 21 TOOK: 0ms OF INDEX: 8
            VALUE: 34 TOOK: 0ms OF INDEX: 9
            VALUE: 55 TOOK: 0ms OF INDEX: 10
            VALUE: 89 TOOK: 0ms OF INDEX: 11
            VALUE: 144 TOOK: 0ms OF INDEX: 12
            VALUE: 233 TOOK: 0ms OF INDEX: 13
            VALUE: 377 TOOK: 0ms OF INDEX: 14
            VALUE: 610 TOOK: 0ms OF INDEX: 15
            VALUE: 987 TOOK: 0ms OF INDEX: 16
            VALUE: 1597 TOOK: 0ms OF INDEX: 17
            VALUE: 2584 TOOK: 0ms OF INDEX: 18
            VALUE: 4181 TOOK: 0ms OF INDEX: 19
            VALUE: 6765 TOOK: 0ms OF INDEX: 20
            ... till index 1000 with always < 10ms for each value
            

            如果您在索引 45 处使用递归,则需要这么长时间:

            斐波那契递归

            public static long getFibonacci(long n) {
                if(n <= 1) {
                    return n;
                } else {
                    return getFibonacci(n - 1) + getFibonacci(n - 2);
                }
            }
            
            ---- PRINT ----
            VALUE: 1134903170 TOOK: 9991ms OF INDEX: 45
            

            【讨论】:

              【解决方案11】:

              [EDIT1] https://www.jdoodle.com/iembed/v0/2N3
              我修复了打印 N_0 的功能,这很酷:

              public class Main
              {
                  public static int f(int n, boolean p, int level, final int deep) {
                      if (n < 2) {
                          if (p || level == deep) System.out.println(1);
                          return 1;
                      } else {
                          int res = f(n-1, true && p, level + 1, deep) + f(n-2, false, level + 1, deep);
                          if (p) {
                              System.out.println(res);
                          }
                          return res;
                      }
                  }
                  public static void main(String[] args) {
                      int n = 10;
                      f(n, true, 0, n-1); // print recursive
                  }
              }
              



              我可以在一个函数中完成,但丢失了 N_0 号,如下所示: https://onlinegdb.com/S1M0SuEPv
              当它被调用时,我将它解释为递归函数堆栈:

              所以返回函数的值会像这个栈:

              我们需要将数字打印成圆圈,所以我包含一个布尔参数 去做吧:

              public class Main
              {
                  public static int f(int n, boolean p) {
                      if (n < 2) {
                          if (p) System.out.println(1);
                          return 1;
                      } else {
                          int res = f(n-1, true && p) + f(n-2, false);
                          if (p) {
                              System.out.println(res);
                          }
                          return res;
                      }
                  }
                  public static void main(String[] args) {
                      System.out.println(1);
                      f(10, true); // print recursive
                  }
              }
              

              结果很漂亮:))

              1 1 2 3 5 8 13 21 34 55 89

              【讨论】:

                【解决方案12】:
                int sum = 1;
                int n1 = 0 , n2 = 1;
                
                for(int i = 0; i < 10; i++)
                {
                    if(i < 1)
                    {
                        System.out.print(i);
                        System.out.print(" ");
                    }
                    else if(i > 1)
                    {
                        System.out.print(sum);
                        System.out.print(" ");
                        sum = n1 + n2;
                        n1 = n2;
                        n2 = sum;
                    }
                }
                

                【讨论】:

                • 请解释一下你的答案,以便以后的读者容易理解。
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2015-01-04
                • 1970-01-01
                • 2013-04-11
                • 1970-01-01
                • 1970-01-01
                • 2022-11-27
                相关资源
                最近更新 更多