Optimizing a bigint fibonacci

helxi brucewayneshit at gmail.com
Wed Dec 6 09:12:08 UTC 2017


This is question not directly related to language concepts, it's 
got more to do with the application. I would appreciate if anyone 
would point to me how I could optimize this bit of code
auto fib(const int n)
{
	import std.bigint;

	if (n == 0)
		return BigInt(0);

	if (n == 1)
		return BigInt(1);

	BigInt next;
	for (BigInt i = 0, j = 1, count = 1; count < n; ++count)
	{
		next = i + j;
		i = j;
		j = next;
	}
	return next;
}

void main()
{
	import std.stdio, std.datetime;

	auto t0 = Clock.currTime;
	writeln(fib(100_000));
	writeln(Clock.currTime - t0);
}



I also noticed that if I try to compute it in the compile time 
with enum x = fib(100000) the compiler freezes. What could cause 
this?


More information about the Digitalmars-d-learn mailing list