You are using a version without Ads of this website. Please, consider donating:

### 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.

 ``1234567891011121314151617181920212223242526272829303132333435`` ``````#include #include #include 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