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.