Created
August 21, 2016 23:42
-
-
Save NamXH/8ddd01dbe96f203f51ef155dbc3f0aba to your computer and use it in GitHub Desktop.
This file contains hidden or 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) { | |
| 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