Skip to content

Instantly share code, notes, and snippets.

@lseongjoo
Last active December 11, 2015 20:09
Show Gist options
  • Save lseongjoo/4653105 to your computer and use it in GitHub Desktop.
Save lseongjoo/4653105 to your computer and use it in GitHub Desktop.
Fibonacci sequence generator
// n번째 피보나치 수열 반환
// n = 0, 1, 2, ...
int fibonacci(int nth)
{
int n1 = 0;
int n2 = 1;
int n3;
// F_0 = 0 , F_1 = 1
if(nth == 0 || nth == 1)
return nth;
// 2번째 수부터는 Fn = Fn-1 + Fn-2
for(int i=1; i<=nth-1; i++)
{
n3 = n1+n2;
n1 = n2;
n2 = n3;
}
return n3;
}
// 재귀형으로 n번째 피보나치 수열 반환
// n = 0, 1, 2, ...
int fibonacciRec(int nth)
{
if(nth == 0 || nth == 1)
return nth;
else
return fibonacciRec(nth - 1) + fibonacciRec(nth - 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment