Topic 1506: Seeking 1+2+3+...+n time limit: 1 seconds Memory limit: 128 Mega Special: No submission: 1261 resolution: 723 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 1: Using constructors 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;}
Solution 2: Simulating recursion with virtual functions
#include <iostream> #include <stdio.h>using namespace Std;class A; A * Array[2];class a{public: virtual unsigned int sum (unsigned int n) { return 0; }}; Class B:public A{public: virtual unsigned int sum (unsigned int n) { return array[!! N]->sum (n-1) +n; }; int sum (int n) { a A; b b; Array[0] = &a; ARRAY[1] = &b; int value = Array[1]->sum (n); return value;} int main () { int n; while (scanf ("%d", &n)!=eof) { printf ("%d\n", SUM (n)); } return 0;}
Solution 3: Using function pointers
#include <iostream> #include <stdio.h>using namespace std;typedef unsigned int (*fun) (unsigned int); unsigned int teminator (unsigned int n) { return 0;} unsigned int sum (unsigned int n) { static fun f[2] = {Teminator,sum}; Return n+f[!! N] (n-1);} int main () { int n; while (scanf ("%d", &n)!=eof) { printf ("%d\n", SUM (n)); } return 0;}
Sword refers to the offer series source -1+2+3+...+n