The sword refers to offer (46) to calculate 1 + 2 + 3 +... + n

Source: Internet
Author: User

Question: 1 + 2 + 3... + N. It is required that keywords such as multiplication and division, for, while, if, else, switch, case, and condition judgment statements cannot be used.

 

Problem Analysis:

You cannot use multiplication or division, so you cannot use the n (n + 1)/2 formula.

If you cannot use for while, you cannot use loops or the like.

 

Use the constructor to solve the problem:

Loop only allows the same code to be repeatedly executed n times. We can define a type and create n instances of this type. At this time, the class constructor will certainly execute n times,

We accumulate N times in the class constructor.

Note: The member variables involved in the accumulation should be static, because each class is unique, rather than each instance.

Class temp {public: temp () {sum + = I; ++ I;} static int getsum () {return sum;} PRIVATE: static int sum; static int I ;}; int temp: Sum = 0; int temp: I = 1; int sum (INT N) {temp * A = new temp [N]; int result = temp: getsum (); Delete [] A; A = NULL; return result ;}

 

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.