Created
August 25, 2013 15:52
-
-
Save jpmec/6334608 to your computer and use it in GitHub Desktop.
Compute the n-th Fibonacci number.
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
#include <iostream> | |
using namespace std; | |
/// Output the n-th Fibonacci number. | |
/// http://en.wikipedia.org/wiki/Fibonacci_number | |
/// | |
int main(int argc, char* argv[]) | |
{ | |
if (argc != 2) | |
{ | |
cerr << "expected fibonacci n" << endl; | |
return -1; | |
} | |
int n = atoi(argv[1]); | |
if (n < 0) | |
{ | |
cerr << "n must be greater than 0." << endl; | |
return -2; | |
} | |
if (n == 0) | |
{ | |
cout << 0; | |
} | |
else if (n == 1) | |
{ | |
cout << 1; | |
} | |
else | |
{ | |
int s0 = 0; | |
int s1 = 1; | |
n -= 1; | |
do | |
{ | |
const int sum = s1 + s0; | |
s0 = s1; | |
s1 = sum; | |
} while (--n); | |
cout << s1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment