Factorials: Iterative vs. Recursive.

Pages: 12
You can make the computation a little simpler if you reduce the terms.
With n = 20 r=3 C(n,r) = n! / (r! * (n-r)!) can reduce to (20*19*18)/3! and somewhat generalized [n*(n-1)*...(n-(r-1))]/r!
Woo! I got it! And with three minutes to spare! Here what I ended with for the recursive part.

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
#include <sys/time.h>
#include <cstdlib>
#include <iostream>

using namespace std;

using std::cout;
using std::endl;
using std::endl;

/* Recursive Version */ 
unsigned long factorial(unsigned long n, unsigned long r){
	if (n == r || r==0) 
		return 1;
	else
	{
		return factorial(n-1,r) + factorial(n-1,r-1);
	}
}

int main() {
    struct timeval stop, start;
	int n, r;
	unsigned long output;
	cout<< "Enter n, r: ";
	cin >> n;
	cin >> r;
	gettimeofday(&start, NULL);
    
	output = factorial(n,r);

	gettimeofday(&stop, NULL);
    cout << "Total is: " << output << std::endl << "Time: " << stop.tv_usec - start.tv_usec << endl; 
    return 0;
}
Topic archived. No new replies allowed.
Pages: 12