How would you write a non-recursive algorithm to calculate factorials?

后端 未结 22 947
不思量自难忘°
不思量自难忘° 2020-12-10 11:39

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

22条回答
  •  自闭症患者
    2020-12-10 12:09

    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 
    struct Factorial 
    {
        enum { value = N * Factorial::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
    }
    

提交回复
热议问题