Coding Problem

06/03/2022 06:49 x[t]c#1
I am working on a project and needing to solve this without using a loop. Any math genius in here able to do this without using a loop?

PHP Code:

while (>= 1)
{
     
* (1);
     
x--;

06/03/2022 12:35 Jeoni#2
1.
Sure. Let's assume you start with
Code:
x = n
y = c
2.
So after the loop ran you have
Code:
x = 0
y = c * (n + 1) * ((n - 1) + 1) * ((n - 2) + 1) * ... * (2 + 1) * (1 + 1)
3.
Let's simplify y, so we can see what is going on.
Code:
y = c * (n + 1) * n * (n - 1) * ... * 3 * 2
y = c * (2 * 3 * ... * n * (n + 1))
y = c * (n+1)!
So it is the factorial.

4.
Now you can replace the code you have there with something like that:
Code:
y = y * factorial(x + 1)
x = 0
5.
The problem is, that the factorial needs a loop / recursion which is to be avoided.
So you may use Stirling's approximation to calculate the factorial without having a loop / recursion.

With best regards

/Edit: On a second thought, you're probably a student in some starting semester and the task is to reformulate that into a recursive function (which performs usually worse than the corresponding iterative approach using a loop). In that case the solution is something like that:
Code:
NumberType GarbageRecursiveFactorial(NumberType x)
{
    if (x > 1)
        return x * GarbageRecursiveFactorial(x - 1);
    else
        return 1;
}

y = y * GarbageRecursiveFactorial(x + 1);
x = 0