Recursive Fibonacci

前端 未结 13 1626
情歌与酒
情歌与酒 2020-12-07 18:52

I\'m having a hard time understanding why

#include 

using namespace std;

int fib(int x) {
    if (x == 1) {
        return 1;
    } else {
         


        
相关标签:
13条回答
  • 2020-12-07 19:24
    int fib(int x) 
    {
        if (x < 2)
          return x;
        else 
          return (fib(x - 1) + fib(x - 2));
    }
    
    0 讨论(0)
  • 2020-12-07 19:25

    By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1. Therefore, you should handle it.

    #include <iostream>
    using namespace std;
    
    int Fibonacci(int);
    
    int main(void) {
        int number;
    
        cout << "Please enter a positive integer: ";
        cin >> number;
        if (number < 0)
            cout << "That is not a positive integer.\n";
        else
            cout << number << " Fibonacci is: " << Fibonacci(number) << endl;
    }
    
    int Fibonacci(int x) 
    {
        if (x < 2){
         return x;
        }     
        return (Fibonacci (x - 1) + Fibonacci (x - 2));
    }
    
    0 讨论(0)
  • 2020-12-07 19:28

    Why not use iterative algorithm?

    int fib(int n)
    {
        int a = 1, b = 1;
        for (int i = 3; i <= n; i++) {
            int c = a + b;
            a = b;
            b = c;
        }           
        return b;
    }
    
    0 讨论(0)
  • 2020-12-07 19:28
    int fib(int n) {
        if (n == 1 || n == 2) {
            return 1;
        } else {
            return fib(n - 1) + fib(n - 2);
        }
    }
    

    in fibonacci sequence first 2 numbers always sequels to 1 then every time the value became 1 or 2 it must return 1

    0 讨论(0)
  • 2020-12-07 19:29

    The reason is because Fibonacci sequence starts with two known entities, 0 and 1. Your code only checks for one of them (being one).

    Change your code to

    int fib(int x) {
        if (x == 0)
            return 0;
    
        if (x == 1)
            return 1;
    
        return fib(x-1)+fib(x-2);
    }
    

    To include both 0 and 1.

    0 讨论(0)
  • 2020-12-07 19:36

    This is my solution to fibonacci problem with recursion.

    #include <iostream>
    using namespace std;
    
    int fibonacci(int n){
        if(n<=0)
            return 0;
        else if(n==1 || n==2)
            return 1;
        else
            return (fibonacci(n-1)+fibonacci(n-2));
    }
    
    int main() {
        cout << fibonacci(8);
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题