[OT] fastest fibbonacci

Andrea Fontana via Digitalmars-d digitalmars-d at puremagic.com
Mon Oct 24 00:49:12 PDT 2016


On Sunday, 23 October 2016 at 13:04:30 UTC, Stefam Koch wrote:
> Hi Guys,
>
> while brushing up on my C and algorithm skills, accidently 
> created a version of fibbonaci which I deem to be faster then 
> the other ones floating around.
>
> It's also more concise
>
> the code is :
>
> int computeFib(int n)
> {
>     int t = 1;
>     int result = 0;
>
>     while(n--)
>     {
>         result = t - result;
>         t = t + result;
>     }
>
>    return result;
> }
import std.stdio;
import std.math: pow;

int computeFib(int n)
{
	if (n==0) return 1;
	
     // Magic :)
	enum magic_1 = 
1.61803398874989484820458683436563811772030917980576286213544862270526046281890244970720720418939113748475;
	enum magic_2 = 
2.23606797749978969640917366873127623544061835961152572427089724541052092563780489941441440837878227;
	return cast(int)((0.5+pow(magic_1,n+1))/magic_2);
	
}

void main()
{

	for(int i = 0; i < 10; ++i) writeln(computeFib(i));
	
}



More information about the Digitalmars-d mailing list