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条回答
beautiful°
2楼-- · 2020-02-10 13:10

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
}
查看更多
劳资没心,怎么记你
3楼-- · 2020-02-10 13:11
long fact(int n) {
    long x = 1;
    for(int i = 1; i <= n; i++) {
        x *= i;
    }
    return x;
}
查看更多
唯我独甜
4楼-- · 2020-02-10 13:12
int total = 1
loop while n > 1
    total = total * n
    n--
end while
查看更多
可以哭但决不认输i
5楼-- · 2020-02-10 13:12
fac = 1 ; 
for( i = 1 ; i <= n ; i++){
   fac = fac * i ;
}
查看更多
仙女界的扛把子
6楼-- · 2020-02-10 13:12

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;
}
查看更多
可以哭但决不认输i
7楼-- · 2020-02-10 13:13
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;
}
查看更多
登录 后发表回答