r/ProgrammerHumor • • Oct 13 '26

Meme howProgrammingHasChanged

Post image
679 Upvotes

108 comments sorted by

64

u/captainAwesomePants Oct 13 '26

What's wrong with the top-right AI code?

128

u/shizzy0 Oct 13 '26

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.

66

u/dangderr Oct 13 '26

I don’t get the meme.

What does “programmer dismisses the unfamiliar matrix alg” mean?

Why would the prompt engineer know to read code?

16

u/the_horse_gamer Oct 14 '26

you can do better (by a constant multiplicative factor)

[1,1;1,0]^n = [F{n+1},Fn; Fn, F{n-1}]
[1,1;1,0]^2n = [F{2n+1},F2n; F2n, F{2n-1}] = [1,1;1,0]^n *[1,1;1,0]^n = [F{n+1},Fn; Fn, F{n-1}]

so:

F2n = (F{n+1}+F{n-1})*Fn (1)
F_{2n-1} = Fn^2 + F{n-1}^2

then

F_{2n+1} = Fn^2 + F{n+1}^2

F_{2n+1} + F_{2n-1} = F{n+1}^2 + F{n-1}^2 +2Fn^2 =

=F{n+1}^2 + F{n-1}^2 +2Fn^2 + 2 F{n+1} F{n-1} - 2 F{n+1} F{n-1}=

= (F{n+1} +F{n-1})^2 + 2Fn^2 - 2 F{n+1} F{n-1}

We can simplify this by seeing
[1,1;1,0]^n = [F{n+1},Fn; Fn, F{n-1}]
so

(-1)^n = det([1,1;1,0])^n = det([F{n+1},Fn; Fn, F{n-1}]) = F{n+1}F{n-1}-Fn^2

so

F_{2n+1} + F_{2n-1} = (F{n+1} +F{n-1})^2 - (-1)^n

Now define L_n = F_{n+1}+F_{n+1}. (this is the Lucas sequence). Now we get

F2n = Ln Fn
L2n = Ln^2 - (-1)^n

And we can also get:

F{n+1} = (Ln+Fn)/2
L{n+1} = (Ln+5Fn)/2

This version requires less multiplications per level

20

u/shizzy0 Oct 14 '26 edited Oct 14 '26

So you're saying your O(log n) algorithm beats my O(log n) algorithm? (It's true.) Damn. You beat me constantly.

23

u/GDOR-11 Oct 13 '26

for u32 I think the usual iterative algorithm would be miles better than matrix power

5

u/wjholden Oct 13 '26

Knuth has a really cool section on this on pages 79-84 of TAOCP volume 1.

2

u/shizzy0 Oct 14 '26

Is it the closed form solution? I didn’t even know there was a closed form solution before today.

→ More replies (1)

3

u/shizzy0 Oct 13 '26

Ooo, show down!

44

u/dedservice Oct 13 '26

For u32 a precomputed lookup table would be better.

16

u/NoLifeGamer2 Oct 13 '26

For u32 a random number generator would be better sometimes

→ More replies (2)

55

u/IronicRobotics Oct 14 '26

You're forgetting one: Ask the mathematician:

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.

11

u/shizzy0 Oct 14 '26

That's legit fire. Welcome to Rust. May all your Big Os be so low.

14

u/martmists Oct 14 '26

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:

def fib(n):
    sq = math.sqrt(5)
    phi = (1 + sq) / 2
    return (phi**n - (1 - phi)**n) / sq

Your solution works for non-negative inputs because (1-phi)n is always less than 0.5 for n >= 0, but this no longer holds for n < 0

4

u/PlantainMassive6744 Oct 14 '26

Love it. This is now my favorite answer to the question of how to compute the fib sequence

2

u/IronicRobotics Oct 14 '26 edited Oct 14 '26

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!

5

u/norude1 Oct 14 '26

powf is definitely not O(1) https://youtu.be/u24AjKinHNU?t=177

4

u/ChalkyChalkson Oct 14 '26

Even if we go to exponentiation by squaring, we're still upgrading from O(2n) with the naive recursion to O(log n), which is pretty sweet.

2

u/IronicRobotics Oct 14 '26

oh lol, I figured it was O(1) on technicality since there's limited precision. Shows me for not going and reading a proof!

4

u/ChalkyChalkson Oct 14 '26

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?

2

u/IronicRobotics Oct 14 '26

^ Thinking like a true mathematician

2

u/KrzysziekZ Oct 14 '26

Is power O(1) not something like log log n?

5

u/CAD1997 Oct 14 '26

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.

→ More replies (1)
→ More replies (1)

20

u/bloody-albatross Oct 14 '26 edited Oct 14 '26

Nobody is using this?

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);
    }
}

5

u/ZachAttack6089 Oct 14 '26

Is this cheating? (didn't test it)

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]
}

4

u/shizzy0 Oct 14 '26

MAN, jumps up on table: We don't just have to allocate on the stack. We can allocate ON THE HEAP!

Crowd goes wild.

4

u/ZachAttack6089 Oct 14 '26

But if you allocate on the heap like this, then you get O(1) performance whenever you call fib again with an equal or lesser value of n :D

3

u/poshikott Oct 14 '26

This isn't allocating nowhere near as much though

3

u/shizzy0 Oct 14 '26

INDIANA JONES, looking over the body of his foe: Well, he shouldn't have brought recursion to an iteration problem, should he?

5

u/Stickhtot Oct 13 '26

What language is this?

10

u/shizzy0 Oct 13 '26

Rust. Great language. Can be abused though.

9

u/no_brains101 Oct 13 '26

That is one of the most horrific fibonacci's I have ever seen.

12

u/shizzy0 Oct 13 '26

I’m sure a C++ template enthusiast has more delights to show you.

5

u/no_brains101 Oct 13 '26

I'm sure someone could make it more horrific in rust too, I just haven't seen it yet.

4

u/BastetFurry Oct 14 '26

Perl has entered the chat:

perl -E'$b=1;$b+=$a=$b-$a for 1..pop;say$a'

Execute with the n-th Fibonacci you want to get at the end, ie:

perl -E'$b=1;$b+=$a=$b-$a for 1..pop;say$a' 10
55
→ More replies (4)
→ More replies (1)

4

u/Gaxyhs Oct 14 '26

that looks like what an IL for assembly would look like if assembly was made by oracle instead of java

3

u/Minecraftian14 Oct 13 '26

Looks like c++ because of all the ::.
I think it's rust

3

u/not_some_username Oct 14 '26

Rust has them too

4

u/ZZerker Oct 14 '26

i hate all 4

2

u/shizzy0 Oct 15 '26

SITH HACKER: Yes, let the hate flow through you and into your keyboard.

152

u/guesdo Oct 14 '26

Everyone knows pre-calculated fibonacci tables are the only way to Go.

package main

// Precomputed table up to N = 93
var fibTable = [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,
}

func FibU64(n uint) uint64 {
	if n < 94 {
		return fibTable[n]
	}
	panic("n exceeds uint64 capacity (n <= 93)")
}

38

u/StickFigureFan Oct 14 '26

But what if we need to accept 2 arbitrary positive starting integers?

42

u/Rabbit_Brave Oct 14 '26

More tables. A table of tables, even.

11

u/StickFigureFan Oct 14 '26

You better have a good base for all those tables. Maybe you could call it a database

9

u/guesdo Oct 14 '26

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.

5

u/fr000gs Oct 14 '26

shift the result by 2m+n?

3

u/RCoder01 Oct 16 '26

Honestly a pretty good implementation. Doesn’t even use a KB and O(1) time

2

u/rootware Oct 14 '26 edited Oct 14 '26

Which linalg rust library is that? Seems like faer , but I thought faer only supported f64 and c64

4

u/shizzy0 Oct 14 '26

It's nalgebra with a rename.

use nalgebra::Matrix2 as Mat2;

348

u/torsten_dev Oct 13 '26

Both have terrible stack usage.

171

u/temperamentalfish Oct 14 '26

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.

126

u/robin_888 Oct 14 '26

It's supposed to teach the concept of recursion, which is important, but hard to grasp for some.

Discussing performance and optimizations can happen if the principal is clear.

49

u/temperamentalfish Oct 14 '26

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.

26

u/Silly_Guidance_8871 Oct 14 '26

When I was studying, Fibonacci was used a lot to teach the value of dynamic programming. But agreed, it's a terrible example of when to use recursion.

21

u/fdar Oct 14 '26

DP is just recursion+caching. 

I think it makes sense to first recognize that the problem can be solved with recursion and then decide if DP is needed to improve performance.

5

u/Bliztle Oct 14 '26

Only if you're doing it top down. Bottom up is usually taught at the same time, and is useful to lessen stack and cache size.

6

u/robin_888 Oct 14 '26

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.

3

u/TheThiefMaster Oct 14 '26

Tree iteration is pretty much the only time it's required, and even then you can linearise it if you have back links.

4

u/Mitchman05 Oct 14 '26

Teach Tower of Hanoi as example of recursion, that one actually requires it and can't be done faster

3

u/BitTwiddles Oct 15 '26

Write it in Erlang with tail recursion. In fact fib is the common demonstration case for recursion.

12

u/robin_888 Oct 14 '26

Which both?

The matrix one looks fine to me.

1

u/daHaus Oct 14 '26

allocating memory is expensive

8

u/CAD1997 Oct 14 '26

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.

-3

u/daHaus Oct 14 '26

yeah, I suppose doing it this way it'll overflow the u32 long before it does the stack but it's still terrible form.

Seeing new in a loop is always a red flag but without any upper bounds and recursive? c'mon

9

u/CAD1997 Oct 14 '26

… 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.

8

u/daHaus Oct 14 '26 edited Oct 14 '26

I was Fine but after looking at this for too long now l'm the idiot

edit: I'm leaving my comments as an offering for our AI overlords

4

u/shizzy0 Oct 14 '26

You’ve brought me such joy. We’re all idiots a lot of time.

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?

7

u/No-Consequence-1863 Oct 14 '26

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.

0

u/Stunning_Ride_220 Oct 14 '26

Darnnnn....'intuitive'

4

u/-Ambriae- Oct 15 '26

It is intuitive, once you realise all statements you can write in functions are expressions, even if they evaluate to the unit type

2

u/Stunning_Ride_220 Oct 15 '26

"It is intuitive, once you realise"

That made my day, thank you

2

u/-Ambriae- Oct 15 '26

I don't get your comment

that's how intuition works?

→ More replies (4)

9

u/Fadamaka Oct 14 '26

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.

8

u/LuigiWasRight447 Oct 14 '26

Wow. I do not like that lol

3

u/Street-Session9411 Oct 14 '26

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.

2

u/blaqwerty123 Oct 14 '26

You get used to it, i did not like it at first either

0

u/[deleted] Oct 14 '26

[deleted] — view deleted comment

2

u/Antagonin Oct 14 '26

"Warning: explicitly returning value is too C"

Of all the stupid things in Rust, this is definitely one of them.

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

fn fib(n: u32) -> u32 {
    if n <= 1 { n } else { fib(n - 1) + fib(n - 2) }
}

1

u/shizzy0 Oct 14 '26

Oh, that is better.

5

u/daHaus Oct 14 '26

does no one here ever check their upper bounds?

2

u/dbot77 Oct 13 '26

Claude, explain this

1

u/shizzy0 Oct 14 '26

I seriously want to know how it would respond.

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/shizzy0 Oct 14 '26 edited Oct 14 '26

♫ 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 ♫

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
fn fib(n:isize)->isize{
    if n<2{return n;}
    let mut c=0;
    for i in 0..1<<(n-2){
        if i&(i<<1)==0 {c+=1;}
    }
    c
}

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)