Question

In: Computer Science

Write a recursive and an iterative function to calculate the nth element in a Fibonacci sequence....

Write a recursive and an iterative function to calculate the nth element in a Fibonacci sequence. A Fibonacci sequence is defined as the element 1, followed by another 1, and each element thereafter is the sum of the previous two elements. For example, the first 9 elements of a Fibonacci sequence are:

  • 1 2 3 5 8 13 21 34

This famous sequence was originally used to predict the growth of rabbit populations!

Once you have each of the functions working for n equal to 40, determine which method is more efficient by timing the two separate function calls and printing out the time required for each method call to return the 40th element in the sequence. Return the 40th element to main and print it. After that, print out a complete Fibonacci sequence from element 1 to element 40, along with its position number.

  1. 1
  2. 1
  3. 2
  4. 3

.       .

.       .

This last part should not be timed.

The timer function you need for this Project is:

                        Date d1 = new Date();

                        long milliseconds = D1.getTime();

                                                OR

                        long start = System.currentTimeMillis();

Turn in the source, output, and a short paragraph explaining the reason the two methods took different amounts of time to execute.

Please write in JAVA

and please write recursive part and iterative part separate!

Solutions

Expert Solution

Thanks for the question.


Below is the code you will be needing  Let me know if you have any doubts or if you need anything to change.


Thank You !!


===========================================================================

import java.util.Date;

public class Fibbonacci {

    public static int recursiveFibbonacci(int nthTerm) {
        if (nthTerm <= 1)
            return 1;
        return recursiveFibbonacci(nthTerm - 1) + recursiveFibbonacci(nthTerm - 2);
    }


    public static int iterativeFibbonacci(int nthTerm) {
        if (nthTerm <= 1) {
            return 1;
        }
        int fib = 2;
        int prevFib = 1;

        for (int i = 2; i < nthTerm; i++) {
            int temp = fib;
            fib += prevFib;
            prevFib = temp;
        }
        return fib;
    }

    public static void main(String args[]) {
        int n = 40;


        long start = System.currentTimeMillis();
        System.out.println(n+"th term using recursion is: "+ recursiveFibbonacci(n));
        long stop = System.currentTimeMillis();
        System.out.println("Total Time take using recursion: " + (stop - start)  + " milliseconds");


        start = System.currentTimeMillis();
        System.out.println(n+"th term using iteration is: "+ iterativeFibbonacci(n));
        stop = System.currentTimeMillis();
        System.out.println("Total Time take using iteration: " + (stop - start)  + " seconds");
    }
}

Time Complexity using Recursion is exponential, and the big O is 2^n whereas the time complexity using iteration is of order n

Hence we can see for a larger number of n here in this case n = 40

the time taken to find the nth value will take 2^40 units of time whereas using iterative approach it will take only 40 units of time.

Hence time taken using recursion will always we greater than the time taken following iterative approach.

=============================================================================

thank you so much !!

please do thumbs up : )


Related Solutions

Part 1: Write a recursive function that will calculate Fibonacci numbers using a recursive definition. Write...
Part 1: Write a recursive function that will calculate Fibonacci numbers using a recursive definition. Write a short program to test it. The input of this program must be a positive integer n; the output is the corresponding Fibonacci number F(n) Part 2: Write an iterative function to calculate Fibonacci numbers. Write a test driver for it. The input of this program must be a positive integer n; the output is the corresponding Fibonacci number F(n). Part 3: Write a...
I have the following question: Write a recursive function to find the Nth element from the...
I have the following question: Write a recursive function to find the Nth element from the top of a stack. For example, if N is 3 the function should return the third element in the stack. Use the following header: template <class Type> Type getNth( stack<Type> & s, int n) Although your function may push and pop values from the stack, it must eventually leave the stack in its original state. Your function may NOT use a help stack or...
PLEASE WRITE IN PYTHON A sequence of integers is said to be Fibonacci-like if each element...
PLEASE WRITE IN PYTHON A sequence of integers is said to be Fibonacci-like if each element of the sequence (except the first two elements) is the sum of the previous two integers in the sequence. For example, the sequence 10, 14, 24, 38, 62, 100, 162, 262 is Fibonacci-like. Note that the first two integers in the above sequence are arbitrary. Each of the remaining integers is the sum of the two integers just before it in the sequence. For...
Write a recursive function in python called make_palindrome that takes a sequence as a parameter and...
Write a recursive function in python called make_palindrome that takes a sequence as a parameter and returns a new sequence that is twice the length of the parameter sequence but that contains the contents of the original in palindrome form. For example, if the sequence "super" is passed into the function, the function will return "superrepus".
( Assembly Language ) Write a program that computes the 7th fibonacci number. The fibonacci sequence...
( Assembly Language ) Write a program that computes the 7th fibonacci number. The fibonacci sequence - 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, … what is the initialization of a, b, and d? - a b d 1 ? ? 1 2 ? ? 1 3 1 1 2 4 1 2 3 5 2 3 5 6 3 5 8 7 5 8 13 wrong initialization - a b d 1 0 1 1 2...
Write a MIPS assembly program to calculate the Fibonacci numbers from 1..n using the recursive method....
Write a MIPS assembly program to calculate the Fibonacci numbers from 1..n using the recursive method. The definition of a Fibonacci number is F(n) = F(n-1) + F(n-2). The implementation must follow the following guidelines: Prompt the user for a number n Allocate heap memory to hold the exact number of elements in the Fibonacci sequence for n Implement recursive Fibonacci method as a subprogram Print the Fibonacci sequence array
PYTHON: Write a recursive function named linear_search that searches a list to find a given element....
PYTHON: Write a recursive function named linear_search that searches a list to find a given element. If the element is in the list, the function returns the index of the first instance of the element, otherwise it returns -1000. Sample Output >> linear_search(72, [10, 32, 83, 2, 72, 100, 32]) 4 >> linear_search(32, [10, 32, 83, 2, 72, 100, 32]) 1 >> linear_search(0, [10, 32, 83, 2, 72, 100, 32]) -1000 >> linear_search('a', ['c', 'a', 'l', 'i', 'f', 'o', 'r',...
(a) The Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence,...
(a) The Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and are characterised by the fact that every number after the first two is the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 114, … etc. By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. We define Fib(0)=0,...
In Python Write a Fibonacci class to calculate next number in the 'Fibonacci' class by the...
In Python Write a Fibonacci class to calculate next number in the 'Fibonacci' class by the 'nxt' method. In this class, the 'val' member is a Fibonacci number. The 'nxt' method will return a 'Fibonacci' object whose value is the next number in Fibonacci series. class Fibonacci (): """A Fibonacci number. >>>a = Fibonacci(): >>>a 0 >>>a.nxt() 1 >>>a.nxt().nxt() 1 >>>a.nxt().nxt().nxt() 2 >>>a.nxt().nxt().nxt().nxt() 3 >>>a.nxt().nxt().nxt().nxt().nxt() 5 >>>a.nxt.nxt().nxt().nxt().nxt().nxt() 8 """ def __init__(self): self.val = 0 def nxt(self): """YOUR SOURCE CODE HERE"""...
In java, Write a recursive function to calculate the sum of the nodes only on even...
In java, Write a recursive function to calculate the sum of the nodes only on even levels of the subtree. please do not add any parameters to do this function. private int sumEvenLevels(Node current){ //you can only pass in root. //code }
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT