r/ProgrammerHumor • • 1d ago

Meme dynamicProgramming

Post image
5.3k Upvotes

140 comments sorted by

View all comments

Show parent comment

1

u/donaldhobson 1d ago
def fib(i):
    a,b,c=0,1,1
    for j in bin(i)[3:]:
        a,b,c=a*a+b*b,(a+c)*b,b*b+c*c
        if j=="1":
            a,b,c=b,c,b+c
    return c

Fast Fibonacci algorithm. O(log(j)) if you ignore that * isn't constant time.

1

u/Lithl 22h ago
const root5 = Math.sqrt(5);
const phi = (1 + root5) / 2;
const psi = (1 - root5) / 2;

function fib(n) {
    return (Math.pow(phi, n) - Math.pow(psi, n)) / root5;
}

Closed-form Fibonacci expression. O(1) if you ignore that exponentiation isn't constant time.

0

u/donaldhobson 11h ago

And if you ignore that floating point errors cause problems at n=70.

Whereas I was using python, which has arbitrary size ints.