求1+2+3+...+n的非循环代码方法

题目简述

今天在牛客网上做到这样一道题,让求1+2+3+…n,但是不能用到循环,if,switch case等判断语句,问该怎么做?

思路

最基本的方法肯定是循环,那么寻找与循环相对应的,那就是递归,而递归总会判断n处于最开端的状态,考虑使用&&逻辑判断语句的短路操作来执行类似if的效果:

1
2
3
4
5
6
int sum(int n)
{
int temp = n;
temp && (temp += sum(temp-1));//类似if(temp == 0) return 0;
return temp;
}

还有另外一种做法:使用TMP,即template元编程,但这样需要在编译时就确定好待求的变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<int n>
class sum
{
public:
enum{val = n + sum<n-1>::val};
};
template<>
class sum<1>
{
public:
enum{val = 1};
};
int main()
{
cout<<sum<6>::val<<endl;//但是需要在编译时就能确定非类型模板参数,而不能延后到运行时,这是一个缺点,也是一个优点
}

or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<int n>
class sum1
{
public:
const static int val = n + sum1<n-1>::val;//其实关键就是在编译期能够确定最终结果,所以上述例子和本例都要使用编译器能够确定的变量,本例是静态常量成员。
};
template<>
class sum1<1>
{
public:
const static int val = 1;
};
int main()
{
cout<<sum1<6>::val<<endl;//但是需要在编译时就能确定非类型模板参数,而不能延后到运行时,这是一个缺点,也是一个优点
}

最早的递归可以在运行时再传n值。