Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In Python:

    def fib(n):
        import math
        r5 = math.sqrt(5)
        x = pow((1 + r5) / 2, n)
        x -= pow((1 - r5) / 2, n)
        return x / r5

  $ python fib.py 4
  3.0

  $ python fib.py 5
  5.0

  $ python fib.py 50
  12586269025.0

  $ python fib.py 5000
  OverflowError: (34, 'Result too large')
So we add arbitrary precision. Uglier, but supports any n:

    def fib(n):
        from math import sqrt
        from decimal import Decimal
        r5 = Decimal(sqrt(5))
        x = pow((1 + r5) / 2, n)
        x -= pow((1 - r5) / 2, n)
        return x / r5

  $ python fib.py 4
  3.000000000000000242931577139

  $ python fib.py 5
  5.000000000000000607328942851

  $ python fib.py 50000
  1.077773489309106593392984005E+10449

  $ python fib.py 50309230
  8.147201098193506535089177522E+10514006
Or does it?

  $ python fib.py 50309230390
  decimal.Overflow: above Emax
This was fun. Computing fib(50309230390) is left as an exercise for the reader.

Wolfram alpha verifies this is correct for Fib 50,000: http://www.wolframalpha.com/input/?i=Fib+50000



returning int(round(x)) could act as a bandaid for the slight error in the results.


This shows nothing but one's ability to code-up a math formula. The blog post goes into much detail about how to solve the problem using matrices and memoization.

Edit: Looks like sillysaurus3 edited his comment.


I wasn't trying to one-up anyone. I thought it was interesting, so I figured others might find it interesting too. In particular, it was surprising to find that there's a closed-form solution for the Fibonacci sequence. Sorry.


Don't be sorry! I found your comment very interesting and was also surprised to find that there exists a closed-form solution.


The whole book is pretty fascinating, "Mathematics for Computer Science" by Lehman and Leighton: http://www.cs.princeton.edu/courses/archive/spring10/cos433/...

The formula came from section 17.3.2, which goes into detail about how to derive it.


Thanks. I like the way they introduce what a proof is in chapter 1, I feel like they have a good, subtle sense of humor. I don't have a mathematical background so it might be a tough read for me, but it seems like a great resource.


Was the purpose of this post to help people prepare for interviews? Does code always have to show off one's ability? This code inspired me to learn about Binet's formula and for that reason I think it was valuable.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: