您的位置:首页 > 其它

一道很有意思的题目,计算sum

2013-10-25 11:00 309 查看
原文来自:http://zhedahht.blog.163.com/blog/static/2541117420072915131422/

我稍微整理了下:

题目是这样的:计算从1加到n,sum = 1+2+3+...+n,不能用乘除法,for,while,if,else,switch,case等以及条件判断和?:操作符

经过对文章以及评论的分析,得出如下的一些解法,很有意思,不在于这道题,而在于不同的思路以及对知识的深入理解:

基本上都是代码,基本都能看得懂的,很短。。。

#include <iostream>
#include <cmath>
using namespace std;

//题目:计算从1加到n,sum = 1+2+3+...+n,不能用乘除法,for,while,if,else,switch,case等以及条件判断和?:操作服

//方法一:C++对象数组的构造初始化,new n个对象出来,将调用构造函数n次
class Temp {
public:
Temp() { ++n; sum = sum + n; }
static void Reset() { n = 0; sum = 0; }
static int GetSum() { return sum; }

private:
static int n;
static int sum;
};
int Temp::n = 0;
int Temp::sum = 0;

int solution_one(int n)
{
Temp::Reset();
Temp *a = new Temp
;
delete []a;
return Temp::GetSum();
}

//方法二:利用递归+虚函数+继承
class A;
A* array[2];

class A {
public:
virtual int sum(int n) { return 0; }
};

class B : public A {
public:
virtual int sum(int n) { return array[!!n]->sum(n-1) + n; }
};

int solution_two(int n)
{
A a;
B b;
array[0] = &a;
array[1] = &b;
return array[1]->sum(n);
}

//方法二其实可以不用虚函数,用函数指针同样可以实现
typedef int (*Fun)(int);

int _solution_two_another(int n)
{
return 0;
}

int solution_two_another(int n)
{
Fun f[2] = { _solution_two_another, solution_two_another };
return n + f[!!n](n-1);
}

//方法三:编译期间完成,利用enum和模板编程
template <int n>
struct solution_three
{
enum Value { N = solution_three<n-1>::N + n};
};
template <>
struct solution_three<1>
{
enum Value { N = 1 };
};

//方法四:递归和&&操作服
int solution_four(int n, int &sum)
{
return n && (sum += n) && solution_four(n-1, sum);
}

//方法五:还是递归
int solution_five(int n)
{
int sum = 0;
n && ( sum = n + solution_five(n-1) );
return sum;
}

//方法六:利用数学公式和对数计算法则
int solution_six(int n)
{
int tmp = exp( log(n) + log(n+1) );
return  tmp >> 1;
}

int main()
{
cout << "one : " << solution_one(100) << endl;
cout << "two : " << solution_two(100) << endl;
cout << "two another : " << solution_two_another(100) << endl;
cout << "three : " << solution_three<100>::N << endl;

int sum = 0;
solution_four(100, sum);
cout << "four : " << sum << endl;

cout << "five : " << solution_five(100) << endl;
cout << "six : " << solution_six(100) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: