• Algorithm --> 求1到n的和


    求1到n的和

      输入n,求和1到n,要求不能使用乘除法,不使用任何if while for 以及三目运算,怎么做?

    版本一

    static int f(int n) {
      n && (n += f(n - 1));
      return n;
    }
    int main (int argc, char const *argv[]) {
      printf("%d
    ", f(100));
      return 0;
    }

    版本二

    C++11的 itoa() 和 accumulate():

    #include <algorithm>
    #include <iostream>
    #include <numeric>
    #include <vector>
    
    int main() {
        int n;
        std::cin >> n;
        std::vector<int> a(n);
        std::iota(a.begin(), a.end(), 1);
        std::cout << std::accumulate(a.begin(), a.end(), 0) << std::endl;
    }

    版本三

    使用递归和函数指针数组

    #include <iostream>
    
    int f(int n) {
        static decltype(&f) c[] { [](int){ return 0; }, f };
        return n + c[n > 0](n - 1);
    }
    
    int main() {
        int n;
        std::cin >> n;
        std::cout << f(n) << std::endl;
    }

    版本四

    模板元编程

    typedef int(*S) (int n);
    
    int memeda(int n)
    {
        return 0;
    }
    
    int yamaidie(int n)
    {
        S M[2] = { memeda, yamaidie };
        return M[!!n](n - 1) + n;
    }
    
    int main()
    {
        int n;
        cin >> n;
        cout << yamaidie(n) << endl;
        system("pause");
        return 0;
    }
  • 相关阅读:
    codevs1430 素数判定
    codevs1212 最大公约数
    codevs1012 最大公约数和最小公倍数问题
    codevs1160 蛇形矩阵
    Debate CodeForces
    Divide Candies CodeForces
    Login Verification CodeForces
    Colorful Bricks CodeForces
    ExaWizards 2019 English D
    Cards and Joy CodeForces
  • 原文地址:https://www.cnblogs.com/jeakeven/p/5060489.html
Copyright © 2020-2023  润新知