【原创】编程练习:求1+2+...+n

题目:求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case 等关键字以及条件判断语句(A?B:C)

 

不能使用的东西囊括了基本的编程工具,

先来看看能使用的方法有哪些,加减法、位移(左右移操作),1+2+。。。+n的计算公式为n*(n+1)/2

n-1能得到,除以2能够用位移操作来完成,将公式拆分为n^2 + n 和除以2两部分,是不是可以用个乘方函数取巧一下?(偷笑)

初步想法代码如下:

 

 1 #include<iostream>
 2 #include<math.h>
 3 
 4 using namespace std;
 5 
 6 int compute(int n)
 7 {
 8     int result = (int)pow(n,2) + n;
 9     result  = result >> 1;
10     return result;
11 }
12 int main()
13 {
14     int result;
15     result = compute(6);
16     cout << result << endl;
17     system("pause");
18     return 0;
19 }

后续的新想法会陆续更新

posted @ 2013-04-26 18:00  karlthas  阅读(340)  评论(1编辑  收藏  举报