Skip to content

Instantly share code, notes, and snippets.

@uxn
Last active August 22, 2022 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uxn/93d8ebf9cd022cb42a54597fe99d4599 to your computer and use it in GitHub Desktop.
Save uxn/93d8ebf9cd022cb42a54597fe99d4599 to your computer and use it in GitHub Desktop.
Quick addition of numbers in Fibonacci code (Zeckendorf representation)
// Based on the paper by Donald Knuth - Fibonacci multiplication - 1988
// Test program: https://godbolt.org/z/1Mn1K59xa
size_t fib_add(size_t a, size_t b)
{
size_t x{(a | b) << 1}, x2{(a & b) << 1}, y, y2;
do
{
y = x & x >> 1 & ~(x >> 2);
const size_t m1{~(y | y << 1)};
x &= m1;
x |= x2 & ~m1;
x |= y << 2;
x2 &= m1;
//
y2 = x2;
x &= ~y2;
x2 = y2 << 1 & y2 >> 2;
const size_t m2{y2 << 1 | y2 >> 2};
x2 |= x & m2;
x |= m2;
} while (y || y2);
return (x | x << 1 & 2) >> 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment