Last active
April 10, 2017 19:06
-
-
Save ggl/38458b57b1eb3945ce447c8bf1d4e458 to your computer and use it in GitHub Desktop.
Fibonacci numbers in D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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