Continuous positive number sequence, so that the sum is specified

Source: Internet
Author: User

Question:

Continuous positive number sequence, so that the sum is specified

Analysis:

I have done a similar problem before. I used to sort two numbers and specify the value of the question first, and then start searching from the two ends. This is actually similar. I used two pointers, however, the two pointers start from the beginning at the same time. During initialization, the first pointer points to 1 and the second Pointer Points to 2. If curr_sum is smaller than the specified sum, the second pointer moves backwards. On the contrary, if curr_sum is greater than the specified sum, the first pointer moves backward.

CodeAs follows:

# Include <iostream> # include <cstdlib> # include <cstdio> using namespace STD; // output sequence void printsequence (INT small, int big) {If (small> big) return; For (INT I = small; I <= big; I ++) cout <I <"; cout <Endl; return;} int main () {int sum = 10001; int small = 1; int big = 2; int middle = (1 + sum)/2; int curr_sum = Small + big; while (small <middle) {If (curr_sum = sum) printsequence (small, big); else {While (curr_sum> sum & Small <middle) // always loops, know that the current sum is smaller than sum {curr_sum = curr_sum-small; small ++; If (curr_sum = sum) printsequence (small, big) ;}} big ++; curr_sum + = big;} return 0 ;}

Summary:

Learning to use pointers, especially multiple pointers, can solve many interesting problems.



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.