首页 > 其他 > 详细

Algorithm --> 求1到n的和

时间:2015-12-20 13:08:27      阅读:212      评论:0      收藏:0      [点我收藏+]

求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\n", 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;
}

 

Algorithm --> 求1到n的和

原文:http://www.cnblogs.com/jeakeven/p/5060489.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!