斐波那契數列的實現
阿新 • • 發佈:2018-03-05
cci || clu include cst eof style span def
C/C++非遞歸實現:
#include<cstdio> #include<iostream> using namespace std; int fibonacci(int n) { int f1,f2,f3=0; f1 = f2 = 1; if(n==1 || n==2) return 1; for(int i=2; i<n; i++) { f3 = f1 + f2; f1 = f2; f2 = f3; } return f3; } int main() {int n; while(scanf("%d", &n) != EOF) { printf("%d\n", fibonacci(n)); } return 0; }
C/C++遞歸實現:
#include<cstdio> #include<iostream> using namespace std; int fibonacci(int n) { if(n==1 || n==2) return 1; return fibonacci(n-1)+fibonacci(n-2); }int main() { int n; while(scanf("%d", &n) != EOF) { printf("%d\n", fibonacci(n)); } return 0; }
python3遞歸實現:
def Fibonacci(n): if (n==1 or n==2): return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) n = int(input()); print(Fibonacci(n))
python3非遞歸實現:
def Fibonacci(n): f1 = f2 = 1 f3 = 0 if (n==1 or n==2): return 1 for i in range(n-2): f3 = f1 + f2 f1 = f2 f2 = f3 return f3 n = int(input()); print(Fibonacci(n))
斐波那契數列的實現