Created
October 30, 2018 08:36
-
-
Save 0xdewy/9d29269110fbda5cb11312000fef52cb to your computer and use it in GitHub Desktop.
This file contains 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
function fib3(uint n) external pure returns(uint a) { | |
if (n == 0) { | |
return 0; | |
} | |
uint h = n / 2; | |
uint mask = 1; | |
// find highest set bit in n | |
while(mask <= h) { | |
mask <<= 1; | |
} | |
mask >>= 1; | |
a = 1; | |
uint b = 1; | |
uint c; | |
while(mask > 0) { | |
c = a * a+b * b; | |
if (n & mask > 0) { | |
b = b * (b + 2 * a); | |
a = c; | |
} else { | |
a = a * (2 * b - a); | |
b = c; | |
} | |
mask >>= 1; | |
} | |
return a; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment