Skip to content

Instantly share code, notes, and snippets.

@0xdewy
Created October 30, 2018 08:36
Show Gist options
  • Save 0xdewy/9d29269110fbda5cb11312000fef52cb to your computer and use it in GitHub Desktop.
Save 0xdewy/9d29269110fbda5cb11312000fef52cb to your computer and use it in GitHub Desktop.
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