That's a standard Taylor series function to compute cosine. The problem isn't with the formula.
Don't ignore the advice you have already been given.
factorial
To compute factorial, you need to compute
two things:
1 The series 1, 2, 3, ..., n-1, n
2 The running product of the terms of that series
Your factorial uses the same variable ('n') for both of those things.
So, suppose you are calculating the factorial of 3. You start with n=1.
k=3,n=1:
n = n * (n+1) = 1 * 2 = 2
n++ = n = 3
n<k+1 = 3<3+1 = 3<4 = true, so:
k=3,n=3
n = n * (n+1) = 3 * 4 = 12
n++ = n = 13
n<k+1 = 13<3+1 = 13<4 = false, so you're done.
|
Do you see where the problem is? You are trying to use
n for two different things.
Try thinking the other way. You are given a value, k. Start with n = 1 and multiply it by k. Decrement k by one and repeat. Stop when k == 1.
That way we get our sequence variable:
1 k, k-1, k-2, ..., 2, 1
2 n is product of terms of sequence K
Hope this helps.