import java.lang.*;
class Fibonacci
{
static private double rootFive
= Math.
sqrt(5); static private double PHI = (1 + rootFive) / 2;
public static void main
(String[] args
) {
long a = 0, b = 1, c;
long num, FSum, sum = 0;
// Greater values of n will over flow long.
// Use higher data type for larger n.
int n = 50;
for (int i = 0; i <= n; i++)
{
if (i == 0 || i == 1) {
c = i == 0 ? a : b;
}
else {
c = a + b;
a = b;
b = c;
}
num = fiboNum(i);
System.
out.
print(fiboIndx
(c
) + ": " + num
); System.
out.
print(tabs
+ "Diff: " + (num
- c
)); sum += c;
FSum = fiboSum(i);
System.
out.
print(tabs
+ "Sum: " + sum
+ tabs
+ "Sum (Formula): " + FSum
); System.
out.
println(tabs
+ "Diff: " + (FSum
- sum
)); }
}
public static long fiboNum(int n)
{
return (long) Math.
floor(Math.
pow(PHI, n
) / rootFive
+ 0.5); }
public static int fiboIndx(long num)
{
if (num == 0) return 0;
return (int) Math.
floor(Math.
log(num
* rootFive
) / Math.
log(PHI
) + 0.5); }
public static long fiboSum(int n)
{
return fiboNum(n + 2) - 1;
}
}
aW1wb3J0IGphdmEubGFuZy4qOwoKY2xhc3MgRmlib25hY2NpCnsKCXN0YXRpYyBwcml2YXRlIGRvdWJsZSByb290Rml2ZSA9IE1hdGguc3FydCg1KTsKCXN0YXRpYyBwcml2YXRlIGRvdWJsZSBQSEkgPSAoMSArIHJvb3RGaXZlKSAvIDI7CgkKCXB1YmxpYyBzdGF0aWMgdm9pZCBtYWluIChTdHJpbmdbXSBhcmdzKQoJewoJCWxvbmcgYSA9IDAsIGIgPSAxLCBjOwoJCWxvbmcgbnVtLCBGU3VtLCBzdW0gPSAwOwoJCS8vIEdyZWF0ZXIgdmFsdWVzIG9mIG4gd2lsbCBvdmVyIGZsb3cgbG9uZy4KCQkvLyBVc2UgaGlnaGVyIGRhdGEgdHlwZSBmb3IgbGFyZ2VyIG4uCgkJaW50IG4gPSA1MDsKCQkKCQlmb3IgKGludCBpID0gMDsgaSA8PSBuOyBpKyspCgkJewoJCQl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