Problem description
For 1+2+ ... +n, you must not use multiplication and division, for, while, if, else, switch, case and other keywords and conditional judgment statements.
The actual significance is not big, the topic involves the knowledge is still good!
Method 1
Solved with a constructor function.
#include <iostream>
using namespace std;
Class Plus
{public
:
Plus () {++i, sum = i;}
Remove the following reset function and try the
static void reset () {i = 0; sum = 0;}
Remove the following static keyword try the
static int getsum () {return sum;}
Private:
static int i;
static int sum;
int plus::i = 0;
int plus::sum = 0;
int cacsum (int n)
{
//only static function can call
plus::reset ();
Plus *test = new Plus[n];
delete[] test;
return Plus::getsum ();
}
int main ()
{
int i = m;
int result = Cacsum (i);
cout << ' result = ' << result << Endl;
System ("pause");
return 0;
}
Method 2
The recursive method is used to solve the sum (n) =sum (n-1) +n
int getsum (int n)
{
int result=0;
(n>0) && (Result=getsum (n-1) +n);
return result;
}
Author: csdn Blog Duplan
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/