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 64 65 66 67
|
#include <iostream>
#include <sys/time.h>
#include <cstdlib>
using std::cout;
using std::endl;
long double factorial(long double n);
long double iterative_func(long double n, long double r);
long double recursive_func(long double n, long double r);
long double myfunction(long double n, long double r);
int main()
{
myfunction(20,3);
myfunction(1000,10);
}
long double myfunction(long double n, long double r)
{
long double result1, result2;
typedef struct timeval time;
time stop, start;
gettimeofday(&start,NULL);
result1 = iterative_func(n,r);
cout<< "Iterative total = "<< result1 << endl;
gettimeofday(&stop, NULL);
if (stop.tv_sec > start.tv_sec)
cout << "Time spent in seconds: " << stop.tv_sec - start.tv_sec << endl;
else
cout << "Time spent in microseconds: " << stop.tv_usec - start.tv_usec << endl;
return 0;
}
long double factorial(long double n)
{
long double total = 1;
long double i;
for (i = 1; i < n; i ++)
{
total *= i;
}
return total;
}
long double recursive_func(long double n, long double r)
{
if (n == r || r == 0)
return 1;
else
return (n/r) * recursive_func(n-1, r-1);
}
long double iterative_func(long double n, long double r)
{
long double total = 1;
total = factorial(n)/ (factorial(r) * factorial(n - r));
return total;
}
|