程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 斐波那契數(C/C++,Scheme)

斐波那契數(C/C++,Scheme)

編輯:C++入門知識

斐波那契數(C/C++,Scheme)


一、背景

斐波那契數的定義:
f0=0
f1=1
fi=fi−1+fi−2(i>1)

二、分析

我引用兩張表,大家一看便懂。

1.遞歸

(factorial 6)
(* 6 (factorial 5))
(* 6 (* 5 (factorial 4)))
(* 6 (* 5 (* 4 (factorial 3))))
(* 6 (* 5 (* 4 (* 3 (factorial 2)))))
(* 6 (* 5 (* 4 (* 3 (2 (factorial 1))))))
(* 6 (* 5 (* 4 (* 3 (* 2 1)))))
(* 6 (* 5 (* 4 (* 3 2))))
(* 6 (* 5 (* 4 6)))
(* 6 (* 5 24))
(* 6 120)
720

2.迭代

(factorial 6)
(factorial 1 1 6)
(factorial 1 2 6)
(factorial 2 3 6)
(factorial 6 4 6)
(factorial 24 5 6)
(factorial 120 6 6)
(factorial 720 7 6)
720

遞歸的核心在於:不斷地回到起點。
迭代的核心在於:不斷地更新參數。

在下面的代碼中,遞歸的核心是sum的運算,sum不斷的累乘,雖然運算的數值不同,但形式和意義一樣。

而迭代的核心是product和counter的不斷更新。如上表中,product就是factorial的前2個參數不斷的累乘更新成第一個參數;而第二個參數則是counter,其不斷的加1來更新自己。

product <- counter * product
counter < - counter + 1

三、代碼

C語言版

#include 
#include 

int factorialRecursive(int n);
int factorialIteration(int product, int counter, int max_count);

int main()
{
    int n;
    printf(Enter an integer: 
);
    scanf(%d,&n);

    printf(%d
,factorialRecursive(n));
    printf(%d
,factorialIteration(1,1,n));

    return 0;
}

int factorialRecursive(int n)
{
    int sum=1;
    if(n==1)
        sum*=1;
    else
        sum=n*factorialRecursive(n-1);
    return sum;
}

int factorialIteration(int product, int counter, int max_count)
{
    int sum=1;
    if(counter>max_count)
        sum*=product;
    else
        factorialIteration((counter*product),(counter+1),max_count);
}

C++語言版

#include 

using namespace std;

int factorialRecursive(int n);
int factorialIteration(int product, int counter, int max_count);

int main()
{
    int n;
    cout<>n;
    cout<max_count)
        sum*=product;
    else
        factorialIteration((counter*product),(counter+1),max_count);
}

四、進階

Scheme語言版

(define (factorial n)
    (if (= n 1)
        1
        (* n (factorial (- n 1)))))
(define (factorial n)
    (fact-iter 1 1 n))
(define (fact-iter product counter max-count)
    (if (> counter max-count)
        product
        (fact-iter (* counter product)
                   (+ counter 1)
                   max-counter)))

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved