Hone logo
Hone
Problems

Calculating the Fibonacci Sequence

The Fibonacci sequence is a classic example in computer science, appearing in various mathematical and computational contexts. This challenge asks you to create a Go function that efficiently calculates the nth Fibonacci number. Understanding and implementing this sequence is fundamental for grasping recursion, dynamic programming, and optimization techniques.

Problem Description

You are tasked with creating a Go function named Fibonacci that takes an integer n as input and returns the nth Fibonacci number. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones. Mathematically, F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1.

Key Requirements:

  • The function must be named Fibonacci.
  • It must accept a single integer argument n.
  • It must return an integer representing the nth Fibonacci number.
  • The function should handle invalid input gracefully (negative values of n).

Expected Behavior:

  • For n = 0, the function should return 0.
  • For n = 1, the function should return 1.
  • For n = 2, the function should return 1.
  • For n = 3, the function should return 2.
  • For n = 4, the function should return 3.
  • For n = 5, the function should return 5.
  • For negative values of n, the function should return -1 to indicate an error.

Edge Cases to Consider:

  • Negative input values for n.
  • Large values of n (consider potential integer overflow if using a naive recursive approach). While overflow isn't explicitly penalized, a more efficient solution that avoids excessive recursion is preferred.

Examples

Example 1:

Input: 5
Output: 5
Explanation: The 5th Fibonacci number is 5 (0, 1, 1, 2, 3, 5).

Example 2:

Input: 0
Output: 0
Explanation: The 0th Fibonacci number is 0.

Example 3:

Input: -2
Output: -1
Explanation: Negative input is considered an error, so -1 is returned.

Example 4:

Input: 10
Output: 55
Explanation: The 10th Fibonacci number is 55.

Constraints

  • n will be an integer.
  • n can be negative, zero, or positive.
  • The function should be reasonably efficient. While a recursive solution is acceptable, iterative solutions are generally preferred for larger values of n.
  • The return value will be an integer.

Notes

Consider using an iterative approach (e.g., using a loop) to calculate the Fibonacci number. This can be more efficient than a purely recursive approach, especially for larger values of n, as it avoids redundant calculations. Think about how to store previously calculated Fibonacci numbers to avoid recomputation. While not required, consider the potential for integer overflow for very large n.

Loading editor...
go