Skip to content

Instantly share code, notes, and snippets.

@NamXH
Created August 21, 2016 23:42
Show Gist options
  • Select an option

  • Save NamXH/8ddd01dbe96f203f51ef155dbc3f0aba to your computer and use it in GitHub Desktop.

Select an option

Save NamXH/8ddd01dbe96f203f51ef155dbc3f0aba to your computer and use it in GitHub Desktop.
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println(Fibonacci(0));
System.out.println(Fibonacci(1));
System.out.println(Fibonacci(2));
System.out.println(Fibonacci(15));
}
public static int Fibonacci(int n)
{
if (n < 0)
{
throw new IllegalArgumentException("n must be non-negative");
}
if (n == 0)
{
return 0;
}
if (n == 1)
{
return 1;
}
int a = 0;
int b = 1;
boolean aIsSmallerThanB= true;
for (int i = 2; i <= n; i++)
{
if (aIsSmallerThanB)
{
a = a + b;
aIsSmallerThanB = false;
}
else
{
b = a + b;
aIsSmallerThanB = true;
}
}
if (aIsSmallerThanB)
{
return b;
}
else
{
return a;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment