Katianie
Katianie

Reputation: 609

SML fibonacci large numbers

I tried to write my own fib function that works for large numbers (over 50) and I had no luck. First I tried the obvious solution but that overflows way to quicly. my next solution was this

    $fun fib(a:int, b:int, index:int) = if(index = 1) then
    $                                      (a+b)
    $                                   else
    $                                       fib(b, (a+b), index - 1);

Unfortunatly this also overflows.

Upvotes: 1

Views: 816

Answers (2)

Makarius
Makarius

Reputation: 2204

Note that in Poly/ML, both structure Int and IntInf offer unbounded (big) integers by default. Since the implementation uses the GNU MP library at the bottom if it, and small machine integers in the range where this is still possible, it is also quite fast.

Upvotes: 0

You need to take a look at the IntInf module, which provides access to arbitrary precision integers.

You can convert from Int.int to IntInf.int using IntInf.fromInt.

Note, for any operations you do on them, you have to use IntInf.<operation> instead of the Int counterpart. This includes things like addition and the likes.

Upvotes: 4

Related Questions