K
Karl Uppiano
Ingo Menger said:Really?
Yes. including all of the console I/O, four seconds and change on my rather
old laptop.
Way too fat, as most java programs.
Depending on what your features and reqirements are. I was adapting the
original algorithm, which is modeled after the actual mathematical
definition, as classically written, but with the enhancement not to have to
recurse to down to zero every time a new value is needed. One could use an
array of big integers, but an array does not grow dynamically (as a map can)
if someone suddenly requires a larger F(n).
How about the following algorithm? (You may want to convert it to real
Java)
bigint fib(bigint n) {
if (n<2) then return 1;
bigint f1 = 1, f2 = 1, i = 2, f3;
while (i < n) {
i++; f3 = f1; f1 = f2; f2 += f3;
}
return f1+f2;
}
This function should compute the first 1000 numbers in no time. Even
the first 100000.
No time? That *is* impressive. Still, it needs to loop n times for any
arbitrary value of n, which is approximately what the algorithm I presented
has to do if it has never seen n that large before. I agree there is the
issue with storage of all n values in a map with my approach, however, once
calculated, the value never need be calculated again, just looked up. In an
application where the algorithm is used more than once, there is no
iteration at all unless n > any previous n. All engineering involves
compromise, isn't it? BTW, Isn't F(0) = 0?