Fibonacci Dynamic Programming

import 'package:test/test.dart';

//Title:  Nth Fibonacci Number using Dynamic Programming
//Author: Richik Chanda
//Email:  richikchanda1999@gmail.com
List<int> dp;
int mod = (1e9 + 7).toInt();

//Get the nth Fibonacci number modulo 10^9 + 7 since it can be a very large number
int getFib(int n) {
  if (dp[n] == -1) dp[n] = (getFib(n - 1) % mod) + (getFib(n - 2) % mod);
  return dp[n] % mod;
}

//Driver
void main() {
  dp = List.generate((1e6 + 1).toInt(), (e) => -1);
  dp[0] = 0;
  dp[1] = 1;

  test("getFib 0 equals 0", () {
    expect(getFib(0), equals(0));
  });

  test("getFib 1 equals 1", () {
    expect(getFib(1), equals(1));
  });

  test("getFib 5 equals 5", () {
    expect(getFib(5), equals(5));
  });

  test("getFib(n) equals getFib(n - 1) + getFib(n - 2)", () {
    expect(getFib(7), equals(getFib(6) + getFib(5)));
    expect(getFib(14), equals(getFib(13) + getFib(12)));
  });
}
Algerlogo

Β© Alger 2022

About us

We are a group of programmers helping each other build new things, whether it be writing complex encryption programs, or simple ciphers. Our goal is to work together to document and model beautiful, helpful and interesting algorithms using code. We are an open-source community - anyone can contribute. We check each other's work, communicate and collaborate to solve problems. We strive to be welcoming, respectful, yet make sure that our code follows the latest programming guidelines.