using namespace std;
fact = fact*j;
Factorial values quickly get huge. You should check what value your current code fails at, which isn’t hard to find out with a decent test set. Then think about using more suitable data types (
long long perhaps?) and protect against over-limit values. If the answer you are looking for is taken to some modulus then perhaps incorporate that into the function.