Skip to content

Instantly share code, notes, and snippets.

@jpmec
Created August 25, 2013 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpmec/6334608 to your computer and use it in GitHub Desktop.
Save jpmec/6334608 to your computer and use it in GitHub Desktop.
Compute the n-th Fibonacci number.
#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