您的位置:首页 > 其它

算法:求1+2+3+...+n

2016-07-10 11:22 363 查看
题目:求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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: