题目:求1+2+3+…+n要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)
如果只是求求1+2+3+…+n这个很简单,利用数学公式就可以计算了
sum=(1+n)*n/2或for循环中 sum += index;
java不太好实现,不过c++很容易就搞定了,只用构造函数
#include <iostream>
using namespace std;
class Temp
{
static int index;
static int sum;
public:
Temp()
{
index++;
sum += index;
}
void show(void)
{
cout<<"n = "<<index<<", Sum = "<<sum<<endl;
}
};
int Temp::index= 0;
int Temp::sum = 0;
int main(void)
{
Temp * t= new Temp[20];
t->show();
delete [] t;
return 0;
}
输出结果:
n = 20, Sum = 210
java要是n不是很大可以使用异常递归可以实现
public class SumDemo {
public static void main(String[] args) {
int n = 900;
int result = test(n);
System.out.println("n=" + n + ",sum=" + result);
}
private static int test(int n) {
try {
int crash = 1 / n;
return n + test(n - 1);
} catch (Exception e) {
}
return 0;
}
}
输出结果:
n=900,sum=405450