Best answer:
Here's a cute Fibonacci trick you can try. It might give you an alternative way to get the answer, or a way to test your results after you've got the simple, boring approach working:
double r5 = Math.sqrt(5.0); // square root of 5, used more than once
double phi = (1.0 + r5) / 2.0; // the famous...
show more
Best answer: Here's a cute Fibonacci trick you can try. It might give you an alternative way to get the answer, or a way to test your results after you've got the simple, boring approach working:
double r5 = Math.sqrt(5.0); // square root of 5, used more than once
double phi = (1.0 + r5) / 2.0; // the famous "golden ratio"
for (int i=0; i<=20; ++i) {
System.out.println(i + " : " + (long)( Math,pow(phi, i) / r5 + 0.5 ));
}
As you should see, the nth Fibonacci number is (φⁿ / √5) rounded to the nearest whole number, where φ=(1+√5)/2 is the Golden Ratio.
Another coding trick, less "mathy" this time, is to code the regular loop using:
int f0=0, f1=1; // Fib(n-1) and Fib(n) values when n=1
Then in the loop use:
f1 = f0 + f1;
f0 = f1 - f0;
...to advance f1 to become Fib(n+1) and f0 now be Fib(n). Cuts down on variables and eliminates the "shift" that you need to do using the "obvious" approach.
4 answers
·
2 weeks ago