C language: 1 + 2 +... + N Solution

Source: Internet
Author: User

Question: 1 + 2 +... + N. the keyword such as multiplication and division, for, while, if, else, switch, and case and the condition judgment statement (? B: C ).
Analysis:This question does not have much practical significance, because there is no such abnormal restriction in software development. However, this question can effectively examine the divergent thinking ability, and the divergent thinking ability can reflect a deep understanding of programming-related technologies.
Usually 1 + 2 +... + N in addition to formula n (n + 1)/2, there are two methods: loop and recursion. Since the use of for and while has been explicitly restricted, the loop can no longer be used. Likewise, recursive functions also need to use the if statement or condition-based judgment statement to determine whether to continue or terminate recursion. However, these two statements are no longer allowed in the question.
We are still making a circular article. The loop only allows the same code to be executed n times. We can achieve this without using for and while. For example, to define a class, if new contains an array of n such elements, the constructor of this class will be called n times. We can put the code to be executed into the constructor. The following code is based on this idea: Copy codeThe Code is as follows: class Temp
{
Private:
Static int N;
Static int Sum;
Public:
Temp () {++ N; Sum + = N ;}
Static void Reset () {N = 0; Sum = 0 ;}
Static int GetSum () {return Sum ;}
};
Int Temp: N = 0; // The value of the static member is the same for all objects. Static members can be initialized, but can only be initialized in vitro.
Int Temp: Sum = 0;
Int solution1_Sum (int n)
{
Temp: Reset ();
Temp * a = new Temp [n];
Delete [];
A = 0;
Return Temp: GetSum ();
}

We can also focus on recursion. Since we cannot determine whether recursion should be terminated, we may define two functions. One function acts as a recursive function, and the other function processes the termination of recursion. What we need to do is to select one of the two functions. From the two options, we naturally think of Boolean variables, such as calling the first function when ture (1) and calling the second function when false (0. Now the problem is to convert the value n to a Boolean value. If two consecutive inverse operations are performed on n, that is !! N, then the non-zero n is converted to true, and the 0 is converted to false. With the above analysis, let's look at the following code:Copy codeThe Code is as follows: class;
A * Array [2];
Class
{
Public:
Virtual int Sum (int n) {return 0 ;}
};
Class B: public
{
Public:
Virtual int Sum (int n) {return Array [!! N]-> Sum (n-1) + n ;}
};
Int solution2_Sum (int n)
{
A;

Array [0] = &;
Array [1] = & B;
Int value = Array [1]-> Sum (n );
Return value;
}

This method uses virtual functions to implement function selection. If n is not zero, execute function B: Sum. If n is 0, execute A: Sum. We can also directly use the function pointer array, which may be more direct:Copy codeThe Code is as follows: typedef int (* fun) (int );
Int solution3_f1 (int I)
{
Return 0;
}
Int solution3_f2 (int I)
{
Fun f [2] = {solution3_f1, solution3_f2 };
Return I + f [!! I] (I-1 );
}

In addition, we can also let the compiler help us complete recursive operations, such as the following code:Copy codeThe Code is as follows: template <int n> struct solution4_Sum
{
Enum Value {N = solution4_Sum <n-1 >:: N + n };
};
Template <> struct solution4_Sum <1>
{
Enum Value {N = 1 };
};

Solution4_Sum <100>: N is the result of 1 + 2 +... + 100. When the compiler sees solution4_Sum <100>, It is a template class.
Solution4_Sum generates code of this type with the parameter 100. However, the type of the parameter 100 must be 99, because solution4_Sum <100 >:: N = solution4_Sum <99 >:: N + 100. This process is recursive until the type of parameter 1. Because the type has been explicitly defined, the compiler does not need to generate it. Recursive compilation ends here. Because this process is completed in the compilation process, the input n must be determined during the compilation process and cannot be entered dynamically. This is the biggest drawback of this method. In addition, the compiler has a limit on the recursive depth of recursive compilation code, that is, the requirement n cannot be too large.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.