isFibonacci static method

bool isFibonacci(
  1. BigInt n
)

Confirms if a given non-negative number n is a Fibonacci number.

This method efficiently checks if n is present in the Fibonacci sequence by generating Fibonacci numbers until n is found or exceeded.

Note: While functionally correct, this implementation builds a list, which might be less memory-efficient for very large n compared to an iterative approach using only two BigInt variables. For optimal memory usage, consider a version that doesn't build the list.

Returns true if n is a Fibonacci number, false otherwise.

Throws an ArgumentError if n is negative.

Implementation

static bool isFibonacci(BigInt n) {
  if (n < BigInt.zero) {
    throw ArgumentError('Input must be a non-negative number');
  }

  final fibonacciSeries = [BigInt.zero, BigInt.one];

  if (n == BigInt.zero || n == BigInt.one) return true;

  while (fibonacciSeries.last < n) {
    final nextFib =
        fibonacciSeries[fibonacciSeries.length - 2] +
        fibonacciSeries[fibonacciSeries.length - 1];
    fibonacciSeries.add(nextFib);
  }

  return fibonacciSeries.last == n;
}