Created
September 12, 2012 17:39
-
-
Save rajkumar-p/3708464 to your computer and use it in GitHub Desktop.
Iterative Fibonacci
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
| int fibonacci(int n) { | |
| int fibonacci_of_n = 0; | |
| // Base condition | |
| if (n == 1 || n == 0) { | |
| return n; | |
| } | |
| else { | |
| // n - 1 | |
| int n_minus_1 = 1; | |
| // n - 2 | |
| int n_minus_2 = 0; | |
| for (int i = 2; i <= n; ++i) { | |
| fibonacci_of_n = n_minus_1 + n_minus_2; | |
| // Shift left | |
| n_minus_2 = n_minus_1; | |
| n_minus_1 = fibonacci_of_n; | |
| } | |
| } | |
| return fibonacci_of_n; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment