Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write an iterative C++ function that inputs a nonnegative integer 11 and returns

ID: 3691422 • Letter: W

Question

Write an iterative C++ function that inputs a nonnegative integer 11 and returns the//th Fibonacci number. 2. Write a recursive C++ function that inputs a nonnegative integer n and returns the nth Fibonacci number. 3. Compare the number of operations and time taken to compute Fibonacci numbers recursively versus that needed to compute them iteratively. 4. Use the above functions to write a C++ program for solving each of the following computational problems. I. Find the exact value of f 100, f 500, and f 1000, where fn is the nth Fibonacci number. What are times taken to Find out the exact values? II. Find the smallest Fibonacci number greater than 1,000,000 and greater than 1,000,000,000. III. Find as many prime Fibonacci numbers as you can. It is unknown whether there are infinitely many of these. Find out the times taken to Find first 10, 20, 30, 40...up to 200 and draw a graph and see the pattern.

Explanation / Answer

Answer for Question:

Iteration:

public class fib{
public static long F(int N){
if (N == 0) return 0;
if (N == 1) return 1;
return F(N-1) + F(N-2);
}
public static void main(String[] args){
for (int N = 0; N < 999999; N++)
System.out.println(N + " " + F(N));
}
}

Recursion:

public class fib {
public static void main(String[] args){
int N = Integer.parseInt(args[0]);
int[] fib = new int[N];
calcFibonacci(N,fib);
}
public static void calcFibonacci(int n, int[] fib){
for(int i = 1 ; i <=n ;i ++){   
if(i == 1) fib[i] = 0 ;
else if(i == 2 ) fib[i] = 1 ;
else fib[i] = fib[i-1] + fib[i-2] ;
System.out.println("index "+i+" fibonacci : "+ fib[i]);
}
}
}
Comparison of fibonacci using recursive and iteration:

Recursion is better than iteration for problems that can be broken down into multiple, smaller pieces.

For example, to make a recursive Fibonnaci algorithm, you break down fib(n) into fib(n-1) and fib(n-2) and compute both parts. Iteration only allows you to repeat a single function over and over again.

However, Fibonacci is actually a broken example and I think iteration is actually more efficient. Notice that fib(n) = fib(n-1) + fib(n-2) and fib(n-1) = fib(n-2) + fib(n-3). fib(n-1) gets calculated twice!

A better example is a recursive algorithm for a tree. The problem of analyzing the parent node can be broken down into multiple smaller problems of analyzing each child node. Unlike the Fibonacci example, the smaller problems are independent of each other.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote