Python has a lot of features that are convenient for math. One of them is operator overloading, or changing how +, -, *, etc., work. We can use this to make numbers of the form a+b5a + b \sqrt{5} easy to work with. Using this feature, we can make a custom Z5 object (so called because the mathematical way of describing this group of numbers is Z(5)\mathbb{Z}(\sqrt{5})) that represents one of these numbers.

If we play our cards right, we never even need to compute 5\sqrt{5}. Let's look at the full unrounded version of Binet's formula:

F(n)=(1+5)n(15)n2n5 F(n) = \frac{(1 + \sqrt{5}) ^ n - (1 - \sqrt{5})^n}{2^n \sqrt{5}}

Similarly to how complex conjugates work, it turns out that (15)n(1 - \sqrt{5})^n will simply be (1+5)n(1 + \sqrt{5})^n with the sign of the 5\sqrt{5} coefficient flipped. This is why Binet's formula always gives an integer result: the integral parts cancel, and the 5\sqrt{5} will cleanly cancel without ever having to be computed. Dividing by powers of 2 is very simple for computers, because that's just chopping off zeros in binary. This lets us implement a new Fibonacci function, as seen opposite.1


  1. I do some work to avoid needing a big division by 2n2^n at the end, to keep the intermediate steps smaller. It's probably more fair to say that Z5(a, b) represents a2+b25\frac{a}{2} + \frac{b}{2} \sqrt{5}.
Code
Output
498454011879264 498454011879264
81104 81104

Python has a lot of features that are convenient for math. One of them is operator overloading, or changing how +, -, *, etc., work. We can use this to make numbers of the form a+b5a + b \sqrt{5} easy to work with. Using this feature, we can make a custom Z5 object (so called because the mathematical way of describing this group of numbers is Z(5)\mathbb{Z}(\sqrt{5})) that represents one of these numbers.

If we play our cards right, we never even need to compute 5\sqrt{5}. Let's look at the full unrounded version of Binet's formula:

F(n)=(1+5)n(15)n2n5 F(n) = \frac{(1 + \sqrt{5}) ^ n - (1 - \sqrt{5})^n}{2^n \sqrt{5}}

Similarly to how complex conjugates work, it turns out that (15)n(1 - \sqrt{5})^n will simply be (1+5)n(1 + \sqrt{5})^n with the sign of the 5\sqrt{5} coefficient flipped. This is why Binet's formula always gives an integer result: the integral parts cancel, and the 5\sqrt{5} will cleanly cancel without ever having to be computed. Dividing by powers of 2 is very simple for computers, because that's just chopping off zeros in binary. This lets us implement a new Fibonacci function, as seen opposite.1


  1. I do some work to avoid needing a big division by 2n2^n at the end, to keep the intermediate steps smaller. It's probably more fair to say that Z5(a, b) represents a2+b25\frac{a}{2} + \frac{b}{2} \sqrt{5}.
Code
Output
498454011879264 498454011879264
81104 81104