## How would you write a non-recursive algorithm to c

2020-02-10 12:34发布

How would you write a non-recursive algorithm to compute `n!`?

22条回答

At run time this is non-recursive. At compile time it is recursive. Run-time performance should be O(1).

``````//Note: many compilers have an upper limit on the number of recursive templates allowed.

template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
``````

``````long fact(int n) {
long x = 1;
for(int i = 1; i <= n; i++) {
x *= i;
}
return x;
}
``````

``````int total = 1
loop while n > 1
total = total * n
n--
end while
``````

``````fac = 1 ;
for( i = 1 ; i <= n ; i++){
fac = fac * i ;
}
``````

For a non-recursive approach, it can't get simpler than this

``````int fac(int num) {
int f = 1;
for (int i = num; i > 0; i--)
f *= i;
return f;
}
``````

``````long fact(int n)
{
long fact=1;
while(n>1)
fact*=n--;
return fact;
}

long fact(int n)
{
for(long fact=1;n>1;n--)
fact*=n;
return fact;
}
``````