搜尋此網誌

[C/C++][費氏數列(Fibonacci Sequence)]

費氏數列(Fibonacci Sequence),簡而言之就是下一項為前兩項的和,其結果為0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946...,在這邊是第0項為0,第一項為1,不過似乎有人是用第一項為1,第二項也為1,沒有第0項

以下是用遞迴的方式寫的

/*
* File Name: Fibonacci.c
* Author: MH
* Since 2011/05/16
* Toolkit: Dev C++
*/

# include <stdlib.h>
# include <stdio.h>

int fib(int n){

    if(n==0)
        return 0;

    if(n==1)
        return 1;

    return (fib(n-1)+fib(n-2));

}

int main(){

    int input, i;

    while(1){

        printf("The 0th number is 0, and the first number is 1\n");
        printf("ex : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ...\n\n");
        printf("Please input an integer to show the last value of Fibonacci Sequence :\n");
        scanf("%d", &input);
        printf("\n");

        if(input<0)
            printf("\nInput cannot less than 0\n\n");

        else{
            for(i=0; i<=input; i++)
                printf("%d  ", fib(i));
        }

        printf("\n\n");

        system("PAUSE");
        system("CLS");

    }

    return 0;

}


不過當然也有用迴圈的方法寫的

/*
* File Name: Fibonacci.c
* Author: MH
* Since 2011/05/16
* Toolkit: Dev C++
*/

# include <stdlib.h>
# include <stdio.h>

int main(){

    int n, i, n_2=0, n_1=1, fib;

    while(1){

        printf("The 0th number is 0, and the first number is 1\n");
        printf("ex : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ...\n\n");
        printf("Please input an integer to show the last value of Fibonacci Sequence :\n");
        scanf("%d", &n);
        printf("\n");

        if (n == 0)
            fib = n_2;

        else if (n == 1)
            fib = n_1;

        else{

            for (i=2; i<=n; i++) {
                fib = n_2 + n_1;
                n_2 = n_1;
                n_1 = fib;
            }

            n_2 = 0;
            n_1 = 1;

        }

        printf("The Fibonacci Sequence is %d\n\n", fib);

        system("PAUSE");
        system("CLS");

    }

    return 0;
}

1 則留言: