Skip to content

Instantly share code, notes, and snippets.

@seifalmotaz
Last active May 8, 2022 22:04
Show Gist options
  • Save seifalmotaz/92599ecf5265704883b83adbb975ca86 to your computer and use it in GitHub Desktop.
Save seifalmotaz/92599ecf5265704883b83adbb975ca86 to your computer and use it in GitHub Desktop.
Fibonacci algorithm in dart (recursion, stack)
// 10000 in 0.16
// 100000 in .278
// 1000000 the computer lagged
// computer specifications
// Device name DESKTOP-KNC2A16
// Processor Intel(R) Core(TM) i5-4460 CPU @ 3.20GHz 3.20 GHz
// Installed RAM 8.00 GB
// System type 64-bit operating system, x64-based processor
// Edition Windows 10 Pro
// Version 21H2
// Installed on ‎3/‎19/‎2021
// OS build 19044.1645
// Experience Windows Feature Experience Pack 120.2212.4170.0
final Map<int, BigInt> cache = {};
void main(List<String> arguments) {
var stopwatch = Stopwatch();
stopwatch.start();
int count = int.parse(arguments.first);
for (var i = 0; i <= count; i++) {
var fibonacci2 = fibonacci(i);
if (i == count) {
stopwatch.stop();
int ms = stopwatch.elapsed.inMilliseconds;
int s = stopwatch.elapsed.inSeconds;
ms = ms - (s * 1000);
print('$s.$ms\n');
print(fibonacci2);
return;
}
}
}
BigInt fibonacci(int n) {
if (cache.containsKey(n)) return cache[n]!;
if (n == 0) return BigInt.zero;
if (n == 1 || n == 2) {
return BigInt.one;
} else {
var value = fibonacciRe(n - 1) + fibonacciRe(n - 2);
cache[n] = value;
return value;
}
}
BigInt fibonacciRe(int n) {
if (cache.containsKey(n)) return cache[n]!;
if (n == 0) return BigInt.zero;
if (n == 1 || n == 2) {
return BigInt.one;
} else {
var value = fibonacci(n - 1) + fibonacci(n - 2);
cache[n] = value;
return value;
}
}
// 10000 in 0.11
// 100000 in .273
// 1000000 the computer lagged
// computer specifications
// Device name DESKTOP-KNC2A16
// Processor Intel(R) Core(TM) i5-4460 CPU @ 3.20GHz 3.20 GHz
// Installed RAM 8.00 GB
// System type 64-bit operating system, x64-based processor
// Edition Windows 10 Pro
// Version 21H2
// Installed on ‎3/‎19/‎2021
// OS build 19044.1645
// Experience Windows Feature Experience Pack 120.2212.4170.0
final List<BigInt> cacheList = [BigInt.zero, BigInt.one, BigInt.one];
void main(List<String> arguments) {
var stopwatch = Stopwatch();
stopwatch.start();
int count = int.parse(arguments.first);
for (var i = 0; i <= count; i++) {
fibonacci(i);
}
stopwatch.stop();
int ms = stopwatch.elapsed.inMilliseconds;
int s = stopwatch.elapsed.inSeconds;
ms = ms - (s * 1000);
print('$s.$ms\n');
print(cacheList.last);
}
BigInt fibonacci(int n) {
if (n == 0) {
var zero = BigInt.zero;
cacheList.add(zero);
return zero;
} else if (n == 1 || n == 2) {
var one = BigInt.one;
cacheList.add(one);
return one;
} else {
var length = cacheList.length;
var bigInt = cacheList.last + cacheList[length - 2];
cacheList.add(bigInt);
return bigInt;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment