对于斐波那契数,若是采用递归的算法,每个递归调用都将触发另外两个递归调用,而这两个中调用任意一个还会触发另外两个的调用。递归调用的时间复杂度O(2^N),空间复杂度为O(N),所以在计算略大的数会花费一定的时间和空间。递归程序如下:
#include<iostream> using namespace std; unsigned long long Fib(size_t num) { if (num < 2) { return num; } else return Fib(num - 1) + Fib(num - 2); } int main() { unsigned long long ret = Fib(10); cout << ret << endl; system("pause"); return 0; }
用迭代方法计算第N 个斐波那契数,时间复杂度O(N),空间复杂度O(1),程序如下:
#include<iostream> using namespace std; unsigned long long Fib(size_t num) { unsigned long long first = 0; unsigned long long second = 1; unsigned long long sum = 0; if (num < 2) return num; else for (size_t i = 2; i <= num; i++) { sum = first + second; first = second; second = sum; } return sum; } int main() { unsigned long long ret = Fib(10); cout <<"Fibonacci(10)="<< ret << endl; system("pause"); return 0; }
时间: 2024-11-03 20:51:51