现在的位置: 首页 > 综合 > 正文

算法习题12:求1+2+…+n 不能使用关键字

2013年07月29日 ⁄ 综合 ⁄ 共 1508字 ⁄ 字号 评论关闭
题目:求1+2+…+n,
要求不能使用乘除法、for、while、if、else、switch、case等关键字
以及条件判断语句(A?B:C)。

被考倒了。。。
用到了:类的静态变量特性,Bool的二值特性,模板元编程!!!,还有就是我的 霸王硬上弓 算法羡慕

//============================================================================
// Name        : IntrestingAdd.cpp
// Author      : YLF
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

int f(int n);
int b(int n);
int c();

//**********************方法一:利用类静态变量*****************
class Value{
public:
	static int n;
	static int sum;
public:
	static void initValue(){
		n = 0;
		sum = 0;
	}
	Value(){
		n++;
		sum += n;
	}
	static int getValue(){
		return sum;
	}

};

int Value::n = 0;
int Value::sum = 0;

//******************方法二,利用模板元编程********************************
template<int N>
struct add{
	enum {result = N + add<N-1>::result};
};

template<>
struct add<0>
{
	enum {result=0};
};

//***********************方法三:利用Bool类型只有01值!!!
int f2(int);
int main() {

	cout<<"1+2+..+100="<<f2(100)<<endl;//f(100);
	cout<<add<100>::result<<endl;

	Value::initValue();
	Value* temp = new Value[100];
	delete[] temp;
	cout<<Value::getValue();

	return 0;
}
//******************本想用递归,结果。。。还是用到了if,不过改进下 成为f2()********************************
int f(int n){
	if(n == 1)
		return 1;
	int sum = 0;
	sum = n + f(n-1);
	return sum;
}
int f2(int n){
	int arr[2];
	arr[0] = 0;
	arr[1] = f(n-1);

	return n + arr[!!n];
}
//***************************方法4:你妹的,老子强奸了你 哈哈哈  10*10*************
int b(int n){
	return n + n+1 + n+2 + n+3 + n+4 + n+5 + n+6 + n+7 + n+8 + n+9;
}

int c(){
	return b(1) + b(11) + b(21) + b(31) + b(41) + b(51) + b(61) + b(71) + b(81) + b(91);
}

抱歉!评论已关闭.