2014-02-22 32 views
2

我一直在瞭解遞歸工作作爲適用於像斐波那契一些例子,也是添加劑的序列,例如下面的一個..此方法是遞歸還是迭代的情況?

int AdditiveSequence(int n, int t0, int t1){ 
    if(n == 0) return t0; 
    if(n == 1) return t1; 
    return AdditiveSequence(n - 1, t1, t0 + t1); 
} 

我想過如何才能申請,並嘗試這樣:

static final double PERCENT = 0.005; 

double Depreciation(int month, double currentValue){ 
    if(month == 0)return currentValue; 
    return Depreciation(month - 1, currentValue -= currentValue * PERCENT); 
} 

但是,這似乎不是一個遞歸,更像是一個迭代,因爲當我在Eclipse調試屏幕中查看它在月== 0上退出並且迭代的currentValue被正確返回時。

在階乘(n)的方法的情況下:

int Factorial(f){ 
    if(f == 1){ 
     return 1; 
    }else{ 
     return f * Factorial(f - 1); 
    } 
} 

似乎達到基本情況,直到推遲計算,然後直到達到將結果返回回落堆棧...

任何人都可以幫助我確定我用上述折舊方法做了什麼,如果它實際上是遞歸或迭代。

+0

它是遞歸我認爲,因爲函數引用自身,所以它像一個鏈,直到條件會成功,所有鏈回去。 – solvator

+0

正如@solvator所說,它肯定是一個遞歸,因爲它自己調用它來計算返回值。 – fejese

+0

請注意,您應該使用'currentValue - (currentValue * PERCENT)',因爲修改當前遞歸中的currentValue沒有意義。 – Ingo

回答

1

這實際上被稱爲尾遞歸,這意味着當你到達遞歸結束時你有結果。這種類型的遞歸很容易轉化爲迭代代碼,往往是由編譯器

static final double PERCENT = 0.005; 

double Depreciation(int month, double currentValue){ 
    if(month == 0)return currentValue; 
    return Depreciation(month - 1, currentValue -= currentValue * PERCENT); 
} 

在你的情況下的電流值被累積的整套方法,這是它適合用於尾遞歸的個人資料的原因。

1

我認爲AdditiveSequence也必須被稱爲尾遞歸,因爲它在完成時也會退出 - 即(n == 1)返回t1;因爲這符合計算...

+0

yes'AdditiveSequence'也是尾遞歸([什麼是尾遞歸](http://stackoverflow.com/questions/33923/what-is-tail-recursion)) – aaronman