Nothing. It’s actually the best. But the joke is the programmer dismisses the unfamiliar matrix power O(log n) algorithm for the familiar recursive O(2n) algorithm. I mean, it doesn’t even add anything. It’s obviously wrong.
use std::f64::consts::{GOLDEN_RATIO};
//Floating Point errors after n> 70.
fn fib(n: u64) -> u64 {
return (GOLDEN_RATIO.powf(n as f64)/f64::sqrt(5.0)).round() as u64;
}
However, since he's not interested in engineering, floating point errors are simply a shortcoming of the computer to engage in ideal mathematics. But he will smugly point out it's technically O(1) since powf is O(1). : )
[I suffered through learning how to write my first lines of Rust for this.]
Alternatively: Computing Binet's formula using symbolic mathematics.
I was about to point out the direct formula but you beat me to it. Though it should be noted yours doesn't work for negative integers, for that you'd want something like this:
Yes, but the recursive formulas were also only for positive integers. (Also, with the rounding, I can force a final integer solution and get rid of the float error up to n=70. Though I suspect rounding this formula here also works.)
Otherwise we also could have gone with a generating equation and cover the whole complex plane!
Easy, just don't use f64, 128 bit gets you a lot further and we always have arbitrary precision systems after. What is that? That erodes any potential speed gain? Who said that was what I was after?
Mat::pow is O(log n)ish. powf is O(1) for any useful model; even a perfectly rounded result can be computed in a bounded maximum number of machine steps.
pub fn fib(mut n: u32) -> u32 {
let mut a = 0;
let mut b = 1;
while n > 0 {
let c = a + b;
a = b;
b = c;
n -= 1;
}
a
}
Looking at the assembly output the compiler even does loop unrolling for this. In fact running it like this it even completely evaluates this version of fib() at compile time while it still does the full recursive call for the recursive version (here called fibr()):
fn main() {
for i in 0u32..10 {
let r = fibr(i);
let j = fib(i);
println!("{r} {j} {}", r == j);
}
}
let mut fib_list: Vec<u32> = vec![1, 1];
fn fib(n: u32) -> u32 {
for i in fib_list.len()..=n {
let a = fib_list[i - 2];
let b = fib_list[i - 1];
fib_list.push(a + b);
}
fib_list[n]
}
Everyone knows pre-calculated fibonacci tables are the only way to Go.
package main
// Precomputed table up to N = 93
varfibTable=[94]uint64{0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170,1836311903,2971215073,4807526976,7778742049,12586268925,20365010974,32951279899,53316290873,86267570772,139583861645,225851432417,365435294062,591286726479,956722020541,1548008747020,2504730767561,4052739514581,6557470282142,10610209796723,17167680078865,27777889875588,44945569954453,72723459830041,117669029784494,190392489614535,308061519399029,498454009013564,806515528412593,1304969537426157,2111485065838750,3416454603264907,5527939669103657,8944394272368564,14472333941472221,23416728213840785,37889062155313006,61305790369153791,99194852524467597,160500642893621388,259695495418088985,420196138311710373,679891633729799358,1100087772041509731,1779979405771309089,2880067177812818820,4660046583584127909,7540113761396946729,12200160344981074638,
}
funcFibU64(nuint)uint64{if n <94{return fibTable[n]}panic("n exceeds uint64 capacity (n <= 93)")}
fibonacci.db I can already see it being vibe coded by tomorrow 🤣 and I can already see the AI generated README with emoji selling you 100x faster than other solutions.
Yeah I'm cringing at all the recursive solutions. Huge stack and so much repeated work. Just try counting how many times fib(5) would be executed to calculate fib(10). It's so often the go-to example for recursion and it's frankly terrible.
I know, but there are so many better examples. Mergesort, for instance. It shows why the concept is important because it breaks the problem into smaller, more manageable problems, without doing repeated work.
Fibonacci should be taught as an example of when a problem can be solved recursively, but shouldn't.
I think in education it is also important to take "wrong" approaches to learn why they are "wrong" and what possible solutions are. If you just teach the "good" examples students might not realize why the naive approach to Fibonacci is problematic.
In other words you might want to teach naive recursion before you teach tail-recursion.
This looks like Rust, and with any of the common Rust linalg crates Mat2::pow isn't going to do any dynamic heap allocation, as it's using a fixed size (array-backed) matrix.
… There's no recursion in the matrix version of fn fib. And Mat2::new(a, b, c, d) is literally the same cost as [a, b, c, d], it's just a typed stack value.
I don't know much about rust, but I am just curious why the last line doesn't have a "return" keyword? Does it just assume the last line is the value to return? Could you include the "return" keyword if you wanted?
If there is no `;` then the last statement is considered the return value. You can include the return if you want but then you also need the `;` at the end.
Yes, iirc for all of your questions. You don't need to use the return keyword in rust. Also I vaguely remember that you cannot even use it in a traditional way because the compiler is going to yell at you.
Rust is unlike traditional programming languages, expression based. Means you either need to complete your functions with an expression rather than a statement (which `return something;` is) or your whole function needs to be an expression. It’s weird at the beginning but after a time it feels natural. You can basically copy the code of a function 1:1 and replace a function call with it and it will compile, which is something that would not work in a traditional language that is solely statement based. You could basically replace the condition of an if-statement with 100 lines of code that evaluates to a boolean value and it would work. Obviously you don’t gain anything from that but imo it’s how things are supposed to be.
♫ Some(body) once told me the monoid was gonna roll me up into an append / I ain't the sharpest Tool in the crate / She was looking kind of Odd, with her FingerTree and Fold / In the shape of an L on her forehead /
Well, the sums start coming and they don't stop suming / Fed to the fold and I hit the ground running / Didn't make sense not to map for fun / Your head gets smart but your tail gets None /
Hey now, you're a monoid, get your mappend on, go fold! / Hey now, you're a monad, get your bind on, compose! / And all that glitters is Gold / Only Some values break the Fold ♫
Idk rust so... what the hell is 2nd string in the last one or is it just imitating random AI noise? Even as an AI Luddite I can't believe it's that bad.
64
u/captainAwesomePants Oct 13 '26
What's wrong with the top-right AI code?
55
u/IronicRobotics Oct 14 '26
You're forgetting one: Ask the mathematician:
However, since he's not interested in engineering, floating point errors are simply a shortcoming of the computer to engage in ideal mathematics. But he will smugly point out it's technically O(1) since powf is O(1). : )
[I suffered through learning how to write my first lines of Rust for this.]
Alternatively: Computing Binet's formula using symbolic mathematics.
20
u/bloody-albatross Oct 14 '26 edited Oct 14 '26
Nobody is using this?
Looking at the assembly output the compiler even does loop unrolling for this. In fact running it like this it even completely evaluates this version of
fib()at compile time while it still does the full recursive call for the recursive version (here calledfibr()):5
u/Stickhtot Oct 13 '26
What language is this?
4
u/ZZerker Oct 14 '26
i hate all 4
152
u/guesdo Oct 14 '26
Everyone knows pre-calculated fibonacci tables are the only way to Go.
2
u/rootware Oct 14 '26 edited Oct 14 '26
Which linalg rust library is that? Seems like
faer, but I thoughtfaeronly supported f64 and c64348
u/torsten_dev Oct 13 '26
Both have terrible stack usage.
11
u/Depnids Oct 14 '26
I don't know much about rust, but I am just curious why the last line doesn't have a "return" keyword? Does it just assume the last line is the value to return? Could you include the "return" keyword if you wanted?
18
u/babypho Oct 14 '26
Idk what I am looking at so I am just going to comment "LGTM" and approve
2
u/Makonede Oct 14 '26
better one
5
u/daHaus Oct 14 '26
does no one here ever check their upper bounds?
2
u/dbot77 Oct 13 '26
Claude, explain this
4
u/Acrobatic-Cat-2005 Oct 15 '26
Seems the only implementation that is not O(2^n) is the top right one?
1
u/EdelWhite Oct 14 '26
eww, monads
2
u/sgmnt Oct 14 '26
Real ones use pihedron's algorithm.
2
u/ExtraTNT Oct 14 '26
fibs = 0:1:zipWith (+) fibs (tail fibs)
fib n = fibs !! n
1
u/donaldhobson Oct 15 '26
1
u/Educational_Key_7635 Oct 16 '26
Idk rust so... what the hell is 2nd string in the last one or is it just imitating random AI noise? Even as an AI Luddite I can't believe it's that bad.
0
u/mehonje Oct 14 '26
def fib(n), do do_fib(0, 1, n)
def do_fib(num1, _num2, 0), do: num1
def do_fib(num1, num2, n), do: do_fib(num2. num1 + num2, n - 1)