Respuesta :
Answer:
Here is the program that contains a recursive and an iterative function to calculate the nth element in a Fibonacci sequence :
import java.util.Scanner; // to take input from user
public class Main {
public static void main(String[] args) { //start of main function
Scanner input = new Scanner(System.in); // creates Scanner class object
System.out.print("Enter the value of n: "); //prompts user to enter n
int n = input.nextInt(); // reads the input value of n from user
System.out.println("Fibonacci using iteration:"); // displays result of iterative method
long start = System.currentTimeMillis(); //computes the time required by iterative method
System.out.printf("Element at index %d = %d \n", n, Iteration(n)); //returns the nth element of fibonacci series
System.out.printf("Time taken: %d ms\n", System.currentTimeMillis() - start); //displays the time taken to return the nth element of fibonacci series using iterative method
int i = 0, j;
for ( j = 1 ; j <= n ; j++ ) { //used to print the fibonacci sequence using iterative method
System.out.printf("%d : %d\n",j, Iteration(i));
i++; }
System.out.println("Fibonacci using recursion:"); // displays result of recursive method
start = System.currentTimeMillis(); //computes the time required by recursive method
System.out.printf("Element at index %d = %d \n", n, Recursion(n)); //returns the nth element of fibonacci series
System.out.printf("Time: %d ms\n", System.currentTimeMillis() - start); //displays the time taken to return the nth element of fibonacci series using recursive method
int ir = 0, jr;
for ( jr = 1 ; jr <= n ; jr++ ) {
System.out.printf("%d : %d\n",jr, Iteration(ir)); //used to print the fibonacci sequence using recursive method
ir++; } }
static int Iteration(int n) { // iterative method for fibonacci series
int a = 0, b = 1, c = 1;
for (int i = 0; i < n; i++) {
a = b;
b = c;
c = a + b; }
return a; }
static int Recursion(int n) { // recursive method for fibonacci series
if ((n == 1) || (n == 0)) { //base case
return n; }
return Recursion(n - 1) + Recursion(n - 2); } } //recursive case
Explanation:
The explanation is provided in the attached document.