fib function

dynamic fib(
  1. int n
)

Returns the nth Fibonacci number considering the sign of n.

If n is negative and even, the result will also be negative. If n is negative and odd, the result will be positive.

Returns an int if the result fits in 64 bits, otherwise a BigInt.

Example:

print(fib(7));  // Output: 13
print(fib(-7)); // Output: 13
print(fib(-8)); // Output: -21
print(fib(50)); // Output: 12586269025

Implementation

dynamic fib(int n) {
  if (n == 0) return 0; // Special case for n = 0
  if (n == 1 || n == -1) return 1; // Special cases for n = ±1

  // Determine the sign based on evenness of n
  int sign = (n.isNegative && n.isEven) ? -1 : 1;
  n = n.abs();

  // Use BigInt for calculation
  BigInt a = BigInt.zero, b = BigInt.one, f = BigInt.one;
  for (int i = 2; i <= n; i++) {
    f = a + b;
    a = b;
    b = f;
  }

  // Adjust sign
  f *= BigInt.from(sign);

  // Return as int if it fits, otherwise as BigInt
  if (f.bitLength <= 63) {
    return f.toInt();
  } else {
    return f;
  }
}