Recursive Function to generate / print a Fibonacci series

前端 未结 4 498
情书的邮戳
情书的邮戳 2020-12-21 18:55

I am trying to create a recursive function call method that would print the Fibonacci until a specific location:

1 function f = fibonacci(n)
2 fprintf(\'The          


        
相关标签:
4条回答
  • 2020-12-21 19:26

    If you HAVE to use recursive approach, try this -

    function out = fibonacci(n)
    fprintf('The valus is %d\n', n)
    
    if (n==1)
        out = 1;
        return;
    elseif (n == 2)
        out = 2;
        return;
    else
        out = fibonacci(n-1) + fibonacci(n-2);
    end
    
    return;
    

    Unlike C/C++, in MATLAB with 'return', one can't return a value, but only the control goes back to the calling function. The output to be returned to the calling function is to be stored in the output variable that is defined at the start of the function.

    EDIT 1: For the entire fibonacci series and which assumes that the series starts from 1, use this -

    N = 16; %// Number of fibonacci numbers needed
    
    all_nums = zeros(1,N);
    all_nums(1) = 1;
    for k = 2:N
        all_nums(k) = fibonacci(k-1);
    end
    

    Gives -

    1     1     2     3     5     8    13    21    34    55    89   144   233   377   610   987
    
    0 讨论(0)
  • 2020-12-21 19:26

    Create a function, which returns Integer:

    func fibonacci(number n : Int) -> Int 
    {
        guard n > 1 else {return n}
        return fibonacci(number: n-1) + fibonacci(number: n-2)
    }
    

    This will return the fibonacci output of n numbers, To print the series You can use this function like this in swift:

    for _ in 0...10
    {
        print(fibonacci(number : 10))
    }
    

    It will print the series of 10 numbers.

    0 讨论(0)
  • 2020-12-21 19:39

    Create a M-file for fibonacci function and write code as given below

    function [ result ] = fibonacci( n )
    
    if n==0|n==1
        result = n;
    
    else
        result = fibonacci(n-2)+fibonacci(n-1);
    end
    end
    

    Write following code in command window of matlab

    for n = 0:10
        fprintf('Fibonacci(%d)= %d\n', n, fibonacci(n));
        end
    

    Output :-

    Fibonacci(0)= 0
    Fibonacci(1)= 1
    Fibonacci(2)= 1
    Fibonacci(3)= 2
    Fibonacci(4)= 3
    Fibonacci(5)= 5
    Fibonacci(6)= 8
    Fibonacci(7)= 13
    Fibonacci(8)= 21
    Fibonacci(9)= 34
    Fibonacci(10)= 55
    
    0 讨论(0)
  • 2020-12-21 19:40

    Try this:

     function f = fibonacci(n)
     if (n==1)
         f= 1;
     elseif (n == 2)
         f = 2;
     else
         f = fibonacci(n-1) + fibonacci(n-2);   
     end
    

    Note that this is also a recursion (that only evaluates each n once):

    function f=fibonacci(n)
      f=additive(n,1,2);
    
    function a=additive(n,x0,x1)
      if(n==1)
        a=x0;
      else 
        if(n==2)
          a=x1;
        else 
          a=additive(n-1,x1,x0+x1);
        end
      end
    
    0 讨论(0)
提交回复
热议问题