GeeksforGeeks » Interview Questions

Interview Question for Software Engineer/Developer about Algorithms

(3 posts)
  1. noob
    guest
    Posted 1 year ago #

    Discuss different ways to get the nth Fibonacci number, what is the problem with recursive solution?

  2. kartik
    Moderator
    Posted 1 year ago #

    Recursive:

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

    The required stack space needed grows exponentially with respect to the parameter n. Large values of n have been shown to cause abnormal program termination.

    Iterative:

    unsigned long fib2(unsigned int n) {
      if (n == 0) {
        return 0;
      }
      else if (n == 1 || n == 2) {
        return 1;
      }
    
      unsigned long prev = 1;
      unsigned long cur = 1;
    
      unsigned int i;
    
      for (i = 3; i <= n; i++) {
        unsigned long tmp = cur;
        cur = cur + prev;
        prev = tmp;
      }
    
      return cur;
    }
    

    Because there is no recursion, the amount of stack space needed does not depend on the parameter n, greatly reducing the risk of stack overflow.

    Source: https://www.securecoding.cert.org/confluence/display/seccode/MEM05-C.+Avoid+large+stack+allocations

  3. S
    guest
    Posted 1 year ago #

    There are several ways to compute n-th Finonacci number: recursive O(2^n), dynamic programming O(n) and using the formula F(n) = [phi ^ n / 2 - 1/2] where phi is the golden ratio : phi = (1 + sqrt(5))/2. To compute the n-th power of a number is O(log n) - treat cases when n is odd or even.


Reply

You must log in to post.

RSS feed for this topic