Last active
December 22, 2015 17:09
-
-
Save wallstop/6504290 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class main | |
{ | |
public static void main(String [] args) | |
{ | |
fib(10); | |
} | |
// These can be inside the function, but it saves computation time not to redefine them everytime | |
static final double alpha = (1 + Math.sqrt(5)) / 2; | |
static final double omega = (1 - Math.sqrt(5)) / 2; | |
public static int fib(int n) | |
{ | |
// Closed form fib | |
int retVal = (int) ((Math.pow(alpha, (n + 1)) - Math.pow(omega, (n + 1))) / (alpha - omega)); | |
if(n == 0 || n == 1) | |
{ | |
// This print gets executed first! | |
System.out.println(retVal); | |
return 1; | |
} | |
else | |
{ | |
// Otherwise, recursively stack prints | |
System.out.println(fib(n-1)); | |
return retVal; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment