# Skillfully sums any number without recursion or loops

Source: Internet
Author: User

On that day, the instructor gave a question and asked us to do it without recursion or loop ~ Sum of 100?

I wrote a code and sent it out today to see if you have any other good methods! I hope I can leave a message in a good way ,,,

The Code is as follows:

// Do not use loops or recursive summation! (C ++/VC +++ 6.0)
# Include <iostream>
Using namespace std;
Class calculate
{
Public:
Calculate ();
Int getsum ();
Static int N;
Static int SUM;
};
Int calculate: N = 0;
Int calculate: SUM = 0;

Calculate: calculate ()
{
N ++; www.2cto.com
SUM + = N;
}

Int calculate: getsum ()
{
ReturnSUM;
}

Void main ()
{
Intmax, min;
Cout <"Enter the sum range:" <endl;
Cout <"input minimum (min> 0):" <endl;
Cin> min;
While (min <0) {// The input in min is invalid. A message is displayed, prompting you to enter the parameter again;
Cout <"the minimum number of inputs (min> 0) is invalid. Enter again:" <endl;
Cin> min;
}
Cout <"input maximum (max> 0 and max> = min):" <endl;
Cin> max;
While (max <0 | max <min) {// the input of max is invalid. A prompt is displayed, prompting you to re-enter it;
Cout <"the maximum number of inputs (max> 0 & max> = min) is invalid. re-enter:" <endl;
Cin> max;
}

Calculate: N = (min-1 );
Calculate * p = new calculate [max-min + 1];
Cout <min <"~ "<Max <" sum: "<p-> getsum () <endl;
Delete [] p;

}

This method is implemented using the call of default constructor of The Destructor and the features of static data members, in fact, the automatic repeated calls of the Destructor here can also use the C ++ container instead of new, as long as the container contains objects, such as vector, because when the container contains class objects, When you define the number of elements, it will automatically call the destructor to initialize the object!

I don't know if you have any other good methods. I 'd like to leave a message to share with you (only available in C/C ++ !)

From wudemiao's column

Related Keywords:
Related Article

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.