Hello I wrote a loop to get the sum of the factorial of given value n divided by n with increasing exponent. To describe it better it looks like this:
But for some reason my loop is always returning the value 1 whenever I input a number. Here's my loop:
int nVal, i, j, k, nProduct = 1, nSum = 0, nFactorial = 1;
float fResult;
for (i = 1; i <= nVal; i++)
{
for (j = 1; j <= nVal; j++)
{
nFactorial *= j;
nSum += nFactorial;
}
for (k = 1; k <= nVal; k++)
{
nProduct *= k;
}
fResult += (nSum * 1.0) / (nProduct * 1.0);
}
Any fixes I can try?
How big will n
get? This can dictate what the type for nProduct
and nFactorial
should be (e.g. int
or long long
or __int128
or double
).
The nested/inner loops are wrong. You only want/need the for
loop for i
.
And you'll [possibly/probably] overflow/underflow if you wait to calculate the ratio. So, do this at each iteration.
Your factorial calculation line was okay. But, the nProduct
calculation was incorrect. The multiplier has to be n
[and not j
].
You don't initialize fResult
, so it starts with a random value (i.e. undefined behavior). This would be flagged if you compiled with -Wall
[and -O2
] to enable warnings.
Remember that:
k! = (k - 1)! * k
And, that:
n**k = n**(k - 1) * n
So, we can build up nFactorial
subterms and nProduct
subterms iteratively, in a single loop.
Here's what I think your code should be like:
// pick _one_ of these:
#if 0
typedef int acc_t;
#endif
#if 0
typedef long long acc_t;
#endif
#if 0
typedef __int128 acc_t;
#endif
#if 1
typedef double acc_t;
#endif
double
calc1(int nVal)
{
int i;
acc_t nProduct = 1;
acc_t nFactorial = 1;
double ratio;
double fResult = 0;
for (i = 1; i <= nVal; ++i) {
nFactorial *= i;
nProduct *= nVal;
ratio = (double) nFactorial / (double) nProduct;
fResult += ratio;
}
return fResult;
}