Fibonacci 함수

Posted at 2008/02/28 11:02 // in Programming // by Daniel
Recursive version
64비트 지원하도록 바꿈.
#include  <stdio.h>   /* Required to use printf() */
typedef unsigned long long u64;
typedef long long i64;
//#define i64   (long long)
/* Function l(n1,n2,n) calculates f(n) using parameters n1 and n2
 *  * to store the two previously calculated Fibonacci numbers */
long long l(long long n1,long long n2,long long n) {
        //printf("l(%lld,%lld,%lld)=%lld\n", n1, n2, n, (n<2 ? n1 : l(n1+n2, n1, n-1)));
    return n<2 ? n1 : l(n1+n2, n1, n-1);
}
/* Function f(n) returns the n'th Fibonacci number
 *  * It uses ALGORITHM 2B: SIMPLE RECURSION
 *   */
long long f(long long n) {
    return l(1,1,n);
}
/* Function f_print(n) prints the n'th Fibonacci number */
void f_print(long long n) {
    printf("%lldth Fibonacci number is %lld\n",n,f(n));
}
/* Function main() is the program entry point in C */
int main(int argc, char* argv[])
{

        long long n=45;
        if (argc > 1)
                n = (long long) atoi( argv[1]);
    f_print(n);
    return 0;
}
Non recursive version
#include <stdio.h>
unsigned int f(int n) {
    int i;
    unsigned int n1=1,n2=1;

    for(i=1; i<=n; i++) {
        n1+=n2;
        n1^=n2^=n1^=n2; /* C trick to swap n1 and n2 */
    }
    return n1;
}
/* Function f_print(n) prints the n'th Fibonacci number */
void f_print(int n) {
    printf("%dth Fibonacci number is %lu\n",n,f(n));
}

int main(int argc, char* argv[])
{

        int n=45;
        if (argc > 1)
                n = atoi( argv[1]);
        f_print(n);

        return 0;
}
테스트용 프로그램이 필요해서 찾았다. http://cubbi.com/fibonacci/c.html
크리에이티브 커먼즈 라이센스
Creative Commons License

이 글에는 트랙백을 보낼 수 없습니다