实现1+2+3...+n,要求不能使用乘除法、循环、条件判断、选择相关的关键字

时间:2022-07-31 05:37:37

实现1+2+3…+n,要求不能使用乘除法、循环、条件判断、选择相关的关键字

用sizeof求二维数组也行

class Test
{

public:
Test()
{
x++;
sum += x;
}
static int GetSum()
{
return sum;
}

private:
static int x;
static int sum;
};

int Test::sum = 0;
int Test::x = 0;



int main()
{
Test* p = new Test[10];
int sum = Test::GetSum();
cout << sum << endl;
delete[] p;
return 0;
}
class A;

A* arr[2];

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


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

int main()
{
A a;
B b;
arr[0] = &a;
arr[1] = &b;

cout << b.getSum(10) << endl;
return 0;
}
typedef int(*fun)(int n);

fun pFun[2];

int get0(int n)
{
return 0;
}

int getSum(int n)
{
return pFun[!!n](n - 1) + n;
}

int main()
{
pFun[0] = get0;
pFun[1] = getSum;

cout << getSum(10) << endl;
return 0;
}
int getSum(int n)
{
int sum = 0;
n && (sum += getSum(n - 1) + n);
return sum;
}

int main()
{
cout << getSum(10) << endl;
return 0;
}