算法:求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++很容易就搞定了,只用构造函数
java要是n不是很大可以使用异常递归可以实现
如果只是求求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
相关文章推荐
- Unity5学习心得-新特性
- 连缀介绍和简单库对象
- HDU1520->树形DP
- Objective C转Swift注意事项(一)合理使用结构体,枚举,extensions
- Android与H5的交互
- 建立字典嵌套,使用get()查询.
- 长短期记忆网络(LSTM)简述
- Minor GC、Major GC和Full GC之间的区别
- 第五章 C++的内存模型和原子操作
- Manacher______ztr loves substring(hdu 5677 BestCoder Round #82)
- Python学习--装饰器
- LockSupport源码探索
- Eclipse启动Tomcat时45秒超时解决方法
- struts2进阶篇(3)
- opencv介绍
- Android开发---动态设置控件颜色
- Android Activity的生命周期
- UIView指定角为圆角
- 文章标题
- C++11并发编程实战