[JOBDU] Topic 1506: Seeking 1+2+3+...+n

Source: Internet
Author: User

Title: Ask 1+2+3+...+n, request cannot use multiplication method, for, while, if, else, switch, case and other keywords and conditional judgment statement (A? B:C).

This question is very interesting, the solution is still relatively difficult to think of, see this problem usually think of three more common methods: The first is also the most easy to think of, with the loop to do, but the topic requirements can not be used for, while; the second we'll think of is a arithmetic progression, with arithmetic progression's summation formula, But the problem is not to use the multiplier method, or not; the third we will gradually think of recursion, it is true that recursion can be done, but the recursive termination conditions need to use if, not as if.

The solution seems difficult to find, the following is a clever solution to the problem, the key is to use the operator && short-circuit characteristics as a recursive termination condition, which is equivalent to replacing if as a recursive termination condition.

1#include <cstdio>2  3 LongAddConst intNLong&sum) {4n && Add (N-1, sum);5     returnSum + =N;6 }7  8 intMain () {9     intN;Ten      while(SCANF ("%d", &n)! =EOF) { One         Longsum =0; Aprintf"%ld\n", add (n, sum)); -     } -     return 0; the}

[JOBDU] Topic 1506: Seeking 1+2+3+...+n

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.