I have a homework problem asking to write an iterative and recursive combination function. place them in a given program to see which takes longer.
I am having a problem with the iterative function. I have gone over it several times and keep getting a mach-o-linker error. I have tried identifying my variables many different ways and still haven't come up with any luck.
any help on this topic would be much appreciated. I think there is a problem with the iterator function or possibly the factorial function, but I am unable to see it for the life of me right now.
thanks again ahead of time
#include <iostream>
#include <sys/time.h>
#include <cstdlib>
using std::cout;
using std::endl;
double iR;
double iN;
typedef unsigned int uint;
uint Factorial(uint n)
{
if (n == 0) return 1;
if (n <= 2) return n;
else return n * Factorial(n - 1);
}
double combination_recursive(double iN, double iR);
double combination_iterative(int iN, int iR);
int main(int argc, const char * argv[]) {
typedef struct timeval time;
time stop, start;
gettimeofday(&start, NULL);
iN = 20.0;
iR = 3.0;
combination_iterative(iN, iR);
gettimeofday(&stop, NULL);
if(stop.tv_sec > start.tv_sec)
cout << "Seconds: " << stop.tv_sec-start.tv_sec << endl;
else
cout << "Micro: " << stop.tv_usec-start.tv_usec << endl;
return 0;
}
double comination_iterative(int, int) {
if (iN == iR) { return 1;}
if (iR == 0 && iN!= 0) { return 1;}
else return (iN * Factorial(iN-1))/Factorial(iN-1)*Factorial(iN-iR);
}
double combination_recursive(double iN, double iR) {
if (iR < 0 || iR > iN) {
return 0;
}
if (iR < 1) {
return 1;
}
if (iN == iR) {
return 1;
}
return combination_recursive(iN - 1, iR) + combination_recursive(iN - 1, iR - 1);
}