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;
}
原文地址:https://www.cnblogs.com/jeakeven/p/5060489.html