226k views
0 votes
The Fibonacci sequence begins with 0 and then 1 follows. All subsequent values are the sum of the previous two. For example, 0, 1, 1, 2, 3, 5, 8, 13. Complete the fibonacci() function, which has an index, n (starting at 0), as a parameter and returns the nth value in the sequence. Any negative index values should return -1. For example, if the input is 7, the output is: fibonacci(7) is _____.

1 Answer

1 vote

Final answer:

The Fibonacci sequence is a numeric sequence where each number is the sum of the two preceding ones. For a given index n, the fibonacci(n) function should return the nth value in the sequence, or -1 if n is negative. The value of fibonacci(7) is 13.

Step-by-step explanation:

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. To complete the fibonacci() function that returns the nth value in the sequence, one can use a simple recursive method or an iterative approach.

Here is a step-by-step explanation for an iterative approach:

  1. Start by checking if the index n is negative. If yes, return -1.
  2. Then check if n is either 0 or 1. In these cases, return n since these are the first two numbers of the Fibonacci series by definition.
  3. Initialize two variables to keep track of the last two numbers in the sequence. We can name them prev1 (previous number) and prev2 (the number before the previous one).
  4. Use a loop that starts from 2 and iterates up to n. In each iteration, calculate the new number by adding prev1 and prev2 and then update prev1 and prev2 to the last two numbers in the sequence.
  5. Once the loop finishes, prev1 will contain the Fibonacci number at the nth position.

If the input is 7, the output of fibonacci(7) will be the 7th number in the sequence which is 13.

User Sinitsynsv
by
7.8k points