Program do obliczania liczb Fibonacciego za pomocą 3 metod.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | // fib.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <math.h> #include <time.h> #include <Windows.h> using namespace std; unsigned long long fib_iter(int n) { if(n==0) return 0; if(n==1) return 1; long long temp1=0LL,temp2=1ll,temp3=0ll; for(int i=2;i<=n;i++) { temp3=temp1+temp2; temp1 = temp2; temp2 = temp3; } return temp2; } unsigned long long fib_rek(int n) { if(n==0) return 0; if(n==1) return 1; return fib_rek(n-1)+fib_rek(n-2); } unsigned long long fib_lin(int n) { return (long long)floor(((1.0/sqrt(5.0))*pow(((1.0+sqrt(5.0))/2.0),(double)n))-((1.0/sqrt(5.0))*pow(((1.0-sqrt(5.0))/2.0),(double)n))); } int _tmain(int argc, _TCHAR* argv[]) { int i; clock_t start,s1,s2,s3,ss1,ss2,ss3; int limit =2500; s1 = clock(); for(i=1;i<=limit;i++) cout << fib_iter(i); ss1 = clock(); s2 = clock(); for(i=1;i<=30;i++) cout << fib_rek(i); ss2 = clock(); s3 = clock(); for(i=1;i<=limit;i++) cout << fib_lin(i); ss3 = clock(); cout << "\nIteracyjnie: " << ss1-s1; cout << "\nRekurencyjnie" << ss2-s2; cout << "\nLinearnie" << ss3-s3 << "\n"; system("pause"); return 0; } |
Show Comments