печать числовых серий Фибоначчи без использования петель - PullRequest
1 голос
/ 02 ноября 2011

Есть ли хак для печати первых 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); 
    }

}

Может быть способ напечатать промежуточные значения в рекурсии, которые будут печатать числа Фибоначчи.

Ответы [ 4 ]

5 голосов
/ 02 ноября 2011

Вы можете использовать хвостовую рекурсию .

1 голос
/ 09 января 2018

с использованием рекурсии: -

  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);
}
}
1 голос
/ 13 октября 2013
 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);                                          
    }
}
0 голосов
/ 21 декабря 2017
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);
    }
  }
}
...