我有一个作业问题要求编写一个迭代和递归组合函数。将它们放在给定的程序中,看看哪个需要更长的时间。
我遇到了迭代函数的问题。我已经检查了好几次,并且不断收到 mach-o-linker 错误。我尝试了很多不同的方法来识别我的变量,但仍然没有找到任何运气。
对此主题的任何帮助将不胜感激。我认为迭代器函数或阶乘函数可能存在问题,但我现在无法终生看到它。
再次提前感谢
#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);
}