For 1+2+...+n, we must not use multiplication and division, for, while, if, else, switch, case and other keywords and conditional judgment statement (A? B:C) _ Programming
Title: Seek 1+2+...+n, the request cannot use multiplication and division method, for, while, if, else, switch, case and so on keyword and conditional judgment statement (A? B:C)
This problem is indeed a bit biased, most people on the internet to give the solution are recursive. public int sum (int n) {if (n==1)
return 1;
Else
Return N+sum (n-1);
Obviously, the condition is used to judge, does not meet the requirements of the subject.
Then according to the idea of the Netizen summed up 6 kinds of methods. Welcome everybody to add positively. Solution1: For programming languages with exception handling capabilities, such as Java and C #. You can use try{}catch{} to complete the conditional judgment of recursion. public int sum (int n)
{
Try
{
int[] array = new INT[N-2];
Return N+sum (n-1);
}
catch (Exception e)
{
return 1;
}
}
Solution2: Alone with a function to deal with recursive termination, with!! Operations to make conditional judgments. Note: From the point of view of logical operation,!! A equals a itself, but in a language that does not have a Boolean variable (such as C),!! An operation can convert a non-0 variable to 1. #include <iostream.h>
Solution3: First define a class and then create an array with n elements of this type, then the constructor for that class is called n times, and we put the cumulative code in the constructor. But Java creates an array with only references to objects and does not instantiate objects, so we use C + + to implement them. #include <iostream>
using namespace Std;
Class Sum
{
Public
Sum ()
{
++count_n;
Sum_n + = Count_n;
}
static void Reset () {count_n = 0;sum_n = 0;}
static int getsum () {return sum_n;} private:static int count_n;
static int sum_n;
};
int sum::count_n = 0;
int sum::sum_n = 0;
int main ()
{
Sum::reset ();
Sum *psum = new sum[100];
Cout<<sum::getsum () <<endl;
return 0;
}
Solution4: Use C + + template element programming. #include <iostream>
using namespace Std;
Template <unsigned n>
Class Sum
{
Public
Enum{sum = N + sum<n-1>::sum};
};
Template<>
Class sum<1>
{
Public
Enum{sum = 1};
};
int main ()
{
cout<<sum<100>::sum<<endl;
return 0;
}
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.