Hello, I am trying to write a program that does combinational logic based off C(n,r)=n!/r!(n-r)! to get the number of combination for a certain number of objects and sets of those objects. Right now I am having trouble with an C2660 Error on my code. All I am trying to do is get the combinations of the user numbers right now. Here is the code.
#include <iostream>
#include <cmath>
using namespace std;
int factorial(int n, int m);
int main()
{
int number;
int object;
cout << "Enter in a number: ";
cin >> number;
cout << "Enter in object number: ";
cin >> object;
cout << endl;
system("pause");
return 0;
}
int factorial(int n, int m)
{
if (n > 1 || m > 1)
return ((n * (factorial(n-1))/((m * factorial(m-1))*((n * factorial(n-1))-(m * factorial(m-1))*factorial((n * factorial(n-1))-(m * factorial(m-1)));
else
return (1);
}
Your factorial function is a mess! As far as that goes just use recursion. If your making "factorial()" complete two tasks then your going to want to break that into two functions(much more readable that way :P).
Decompose, decompose, decompose...
Examples if you don't follow me:
Lets say I have function "A" which I made to add then multiply two numbers:
1 2 3 4 5
int A(int x, int y) {
int temp = (x + y);
temp = temp + (x * y);
return (temp);
}
Easy, but as functions get bigger their harder to understand(for me at least...) so we could break down function "A"(or decompose, if you will). So now we have two functions "B" and "C".
1 2 3 4 5 6
//C();
int C(int x, int y)
{
return (x+y);
}
1 2 3
int B(int x, int y) {
return (x*y);
}
Good?
EDIT: Sorry if I sound like an idiot(an idiot sounding like an idiot... thats not possiable[saying this with sarcasm]), but I'm quite tired and need sleep(every caffeine jockey does every 5 to 8 weeks). That and I don't expect somone to use the above functions, but I didn't test them to see if they compile. Cheers! Sorry for spelling errors...
You got confused: You started out thinking "I need a factorial function" and ended up writing the COMBINATIONS formula inside the factorial function. The factorial function is really simple:
1 2 3 4 5 6 7 8
typedefunsignedint uint;
uint Factorial(uint n)
{
if (n == 0) return 1;
if (n <= 2) return n
elsereturn n * Factorial(n - 1);
}
Now you can use the factorial function in a second function: uint NumCombinations(uint n, uint m);