Algorithm --> 求1到n的和

时间:2023-03-09 02:46:53
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\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(), );
std::cout << std::accumulate(a.begin(), a.end(), ) << std::endl;
}

版本三

使用递归和函数指针数组

#include <iostream>

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

版本四

模板元编程

typedef int(*S) (int n);

int memeda(int n)
{
return ;
} int yamaidie(int n)
{
S M[] = { memeda, yamaidie };
return M[!!n](n - ) + n;
} int main()
{
int n;
cin >> n;
cout << yamaidie(n) << endl;
system("pause");
return ;
}