Topic 1506: Seeking 1+2+3+...+n time limit: 1 seconds Memory limit: 128 Mega Special: No submission: 1260 Resolution: 722 Title Description: Ask for 1+2+3+...+n, cannot use multiplication method, for, while, if, else, switch, Case keyword and conditional judgment statement (A? B:C). Input: The input may contain multiple test samples. For each test case, the input is an integer n (1<= n<=100000). Output: Corresponds to each test case and outputs the value of the 1+2+3+...+n. Sample input: 35 Sample output: 615
Solution one: Using a construction method to simulate loops
#include <iostream> #include <stdio.h>using namespace Std;class temp{public: Temp () { n++; sum+=n; } static void Reset () { n=0; sum=0; } static unsigned int getsum () { return Sum; } Private: static unsigned int N; static unsigned int Sum;}; unsigned int temp::n = 0;unsigned int temp::sum = 0;unsigned int Sum (int N) { temp::reset (); Temp::reset (); Temp*a = new Temp[n]; Delete[] A; A = NULL; return Temp::getsum ();} int main () { int n; while (scanf ("%d", &n)!=eof) { printf ("%d\n", SUM (n)); } return 0;}
The sword refers to the offer series source code-beg 1+2+3+...+n