c++ - Sum 1 ~ N,不使用乘法、除法、if、while、for、switch和三元表达式

标签 c++ templates

今天,我试着和我的 friend 一起解决一个奇怪的(某种)问题。

Try to get the sum of 1 + 2 + ··· + n, without using multiplication and division, for, while, if, else, switch, case, ternary expression and other keywords.

这是我们的解决方案

  • 构造函数

    class Sum
    {
    public:
        Sum() { ++num; sum += num; }
        static void Init() { num = 0; sum = 0; }
        static unsigned int SumValue() { return sum; }
    private:
        static unsigned int num;
        static unsigned int sum;
    };
    unsigned int Sum::num = 0;
    unsigned int Sum::sum = 0;
    
    unsigned int get_sum(unsigned int n)
    {
        Sum::Init();
    
        Sum * tmp = new Sum[n];
        delete[] tmp;
    
        return Sum::SumValue();
    }
    
  • 递归

    class Ba
    {
    public:
        virtual unsigned int sum(unsigned int n)
        {
             return 0;
        }
    };
    
    Ba* sumArray[2];
    
    class D : public Ba
    {
    public:
         virtual unsigned int sum(unsigned int n)
         {
              return sumArray[!!n]->sum(n - 1) + n;
         }
    };
    
    unsigned int get_sum2(unsigned int n)
    {
        Ba b;
        D d;
        sumArray[0] = &b;
        sumArray[1] = &d;
    
        return sumArray[1]->sum(n);
    }
    

我们认为也许这个问题可以通过 var template 来解决?然而,我们没能弄明白。是否可以使用 template 来做到这一点?

顺便说一句,我们试图在此站点中找到相同的问题,但我们失败了。如果是的话,很抱歉这个重复的问题。

最佳答案

使用最少的关键字,使用短路评估

unsigned sum(unsigned n) {
    unsigned i=0;
    n && (i=n+sum(n-1));
    return i;
}

关于c++ - Sum 1 ~ N,不使用乘法、除法、if、while、for、switch和三元表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34154875/

相关文章:

c++ - 未找到 assimp-vc140-mt.dll ASSIMP

c++ - boost asio async_read_some 超时

c++ - 在 '=' 分隔符上逐行拆分文本文件 C++

c++ - 在这种情况下,是否有与 C++03 的 constexpr 类似的东西?

django - 无法在 Django 模板中渲染 View

c++ - 将类(mixins)的功能与歧义调用结合起来

c++ - 我可以在 for 循环的 init-expression 中使用不同的类型吗?

c++ - 重载 > 运算符在应该返回 false 时返回 true

c++ - 如何使用折叠表达式创建 N 个浮点值的数组?

c++ - 私有(private)类型的模板特化