Skip to content

Instantly share code, notes, and snippets.

@ggl
Last active April 10, 2017 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggl/38458b57b1eb3945ce447c8bf1d4e458 to your computer and use it in GitHub Desktop.
Save ggl/38458b57b1eb3945ce447c8bf1d4e458 to your computer and use it in GitHub Desktop.
Fibonacci numbers in D
import std.stdio;
import std.bigint;
import core.checkedint;
void main() {
writefln("%d", fib_iter(72));
writefln("%d", fib_binet(72));
}
auto fib_iter (int n) {
int k;
ulong a = 0;
ulong b = 1;
bool overflow = false;
if (!overflow) {
foreach (number; 0..n) {
// should overflow at n = 92
ulong c = a;
a = b;
b = addu(a, c, overflow);
if (overflow) {
k = number + 1;
break;
}
}
}
else {
// overflow; continue from k with bigints
BigInt ab = a;
BigInt bb = b;
foreach (number; k..n) {
BigInt cb = ab;
ab = bb;
bb = ab + cb;
}
return ab;
}
// we need to upgrade to bigint
return BigInt(a);
}
auto fib_binet (int n) {
real phi = (1 + 5.0^^0.5) / 2;
// should lose precision at n = 72
return cast(ulong)((phi^^n - (1 - phi)^^n) / 5.0^^0.5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment