不使用循环打印斐波那契数字系列

时间:2011-11-02 18:28:57

标签: java algorithm fibonacci

在没有调用循环的情况下打印第一个n个斐波那契数字是否存在攻击

for(int i=1; i<n; i++)
    System.out.println(computeF(n));

来自主程序?

public static int computeF(int n)
{
    if(n==0)
    {
        return 0;
    }
    else if(n==1)
    {
        return 1;
    }
    else
    {
        return computeF(n-1)+computeF(n-2); 
    }

}

可能有一种方法可以在递归中打印中间值,这将打印斐波那契数字。

5 个答案:

答案 0 :(得分:5)

您可以使用tail recursion

答案 1 :(得分:1)

 public class Fid   
  {   
    static int n1=0;
    static int n2=1;
    static int nex=0;
    public static  void fb(int n)
 {
   if(n<10)
    {
      if(n==0)
       {
         System.out.print(" "+n);
         n++;
         fb(n);
       }
        else
           if(n==1)
       {
         System.out.print(" "+n);
         n++;
         fb(n);
       }

        else{ 
            nex=n1+n2;
            System.out.print(" "+nex);
            n1=n2;
            n2=nex;
            n++;
            fb(n);                
            }           
      }        
    }
    public static void main(String[] args)
    {
      fb(0);                                          
    }
}

答案 2 :(得分:1)

使用递归: -

  class FibonacciRecursion
{
private static int index = 0;
private static int stoppingPoint = 9;

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

  fibonacciSequence(n1, n2);
}

public static void fibonacciSequence(int n1, int n2)
{
  System.out.println("index: " + index + " -> " + n1);

  // make sure we have set an ending point so this Java recursion
  // doesn't go on forever.
  if (index == stoppingPoint)
    return;

  // make sure we increment our index so we make progress
  // toward the end.
  index++;

  fibonacciSequence(n2, n1+n2);
}
}

答案 3 :(得分:0)

/// Java程序,最多可打印用户给出的n个术语的斐波那契数列,而无需使用循环

import java.util。*;

公共类斐波那契 {

public static void main(String []参数)   {

Scanner s = new Scanner(System.in);
System.out.print("Enter the no of terms :");
int no_of_terms= s.nextInt(),a=1,b=0,c=0,count=1;
System.out.print("0 ");//printing the first term
fib(no_of_terms,a,b,c,count);}

公共静态空值fib(int no_of_terms,int a,int b,int c,int count)   {

//when value of count will be equal to the no of terms given by user the program will terminate

if (count==no_of_terms)
   System.exit(0);
else
{
  count++;
  System.out.print(a+" ");
  c=b;
  b=a;
  a=b+c;//calculating the next term
  fib(no_of_terms,a,b,c,count);//calling the function again with updated value
}

} }

答案 4 :(得分:-1)

import java.util.*; 
public class Fibonacci{
  public static void main(String[] args) {    
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a no.");
    int n= sc.nextInt(),a=1,b=0,c=0;
    num(n,a,b,c);
  }
  public static void num(int n,int a,int b,int c){
    if(a<=n){
      System.out.println(a);
      c=b;
      b=a;
      a=b+c;
      num(n,a,b,c);
    }
  }
}