Skip to content

Instantly share code, notes, and snippets.

@abranhe
Last active September 4, 2018 20:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abranhe/5ae241d371dacfa51a2f5116fce3c19f to your computer and use it in GitHub Desktop.
Save abranhe/5ae241d371dacfa51a2f5116fce3c19f to your computer and use it in GitHub Desktop.
Fibonacci

Fibonacci formula:

fib n = floor (phin/√5 + 1/2)

fib n ~= phin/√5

How many digits is fib n?

numDigits (fib n) = log (fib n) = log (phin/√5) = log phin - log √5 = n * log phi - log √5

numDigits (fib n) = n * const + const

it's O(n)

Since the requested result is of O(n), it can't be calculated in less than O(n) time.

If you only want the lower digits of the answer, then it is possible to calculate in sub-linear time using the matrix exponentiation method.

Fibonacci.java

import java.lang.Math;
public class Main {
public static double inverseSqrt5 = 1 / Math.sqrt(5);
public static double phi = (1 + Math.sqrt(5)) / 2;
public static int fibonacci(int n) {
return (int)Math.floor(Math.pow(phi, n) * inverseSqrt5 + 0.5);
}
public static void main(String[] args) {
System.out.println("Fib 1 = " + fibonacci(1));
System.out.println("Fib 2 = " + fibonacci(2));
System.out.println("Fib 3 = " + fibonacci(3));
System.out.println("Fib 4 = " + fibonacci(4));
System.out.println("Fib 5 = " + fibonacci(5));
System.out.println("Fib 6 = " + fibonacci(6));
System.out.println("Fib 7 = " + fibonacci(7));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment