Skip to content
Advertisement

Fibonacci calculator with BigIntegers

I’m working on a homework project where I must have the user input a number, and the computer spits out the Fibonacci numbers up to that one. I’d normally be able to do this, with int values, except that for this program, I need to use the BigInteger type instead, because int, long, double, etc. types are too small to hold the values I’ll need. So, this is the code I’ve got. The problem is that it doesn’t print the numbers it’s supposed to. My imports:

JavaScript

And the rest of the code:

JavaScript

I know it should work, because I was able to use it with the int type, but then I started to need values that were waaay bigger, so I was forced into BigInteger. Can someone see what’s wrong with it? I think the problem is in the return for fibonacci2 method.

Advertisement

Answer

The return value is the one that needs to be a BigInteger, not your argument number. Your initial tests are 1 and 2 (not 0 and 1 – which is how developers count). Basically, the quick and dirty solution is something like

JavaScript

If you need to calculate large values then I suggest using a memoization like

JavaScript

Note that fibonacci3 will be significantly faster than the initial recursive version.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement