Algorithm --> 求1到n的和

不常规求和方法
本文介绍了四种不使用传统循环和条件判断的方法来实现1到n的累加:使用递归和逻辑与操作、利用C++标准库函数如accumulate和iota进行累加、通过递归及函数指针数组实现累加、借助模板元编程完成累加任务。

求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;
}

 

转载于:https://www.cnblogs.com/jeakeven/p/5060489.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值