Skip to content

Instantly share code, notes, and snippets.

@wallstop
Last active December 22, 2015 17:09
Show Gist options
  • Save wallstop/6504290 to your computer and use it in GitHub Desktop.
Save wallstop/6504290 to your computer and use it in GitHub Desktop.
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