Last active
August 22, 2022 04:19
Quick addition of numbers in Fibonacci code (Zeckendorf representation)
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
// 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