Title: Enter a positive n, output all and n consecutive positive sequence. For example, input 15, because of 1+2+3+4+5=4+5+6=7+8=15, so output 3 sequential sequence 1-5, 4-6 and 7-8.
Method One: Record the sequence length, determine whether the first item satisfies the condition can first think of is arithmetic progression, and the variance is 1 positive arithmetic progression, we only need to record a sequence length, according to arithmetic progression formula sum = Na1+n (n-1) *d/2; we can get NA1 = Sum-n (n-1 )/2; Just Judge A1 is greater than 0, where n is the length of the sequence we record. The specific procedures are as follows:
void continuesum (int sum) { int n = 2, na1 = 0; while (n (n+1) <= 2*sum) { na1 = Sum-((n-1) *N/2); if (na1/n > 0 && na1% n==0) { int t = na1/n; cout << T << "-" << t+n-1 << Endl; } n++;} }
Method two: Maintenance sequence of the first two element values, as well as the current sequence and we can also use another method, reference click to open the link, the original program exists in the problem is resolved, its specific practice is based on the first element must not be greater than SUM/2, and the last element can not be greater than sum. When the current sequence and greater than sum, minus the first item, and then the first item plus one, (that is, remove the first element from the sequence), when the current sequence and less than sum, the tail item plus one, that is, add the element.
void continuesumother (int sum) { int start=1, ends=2, mid = SUM/2, cursum = 3; while (Start <= mid && ends < sum) { if (cursum = = sum) { cout<<start<< "-" < <ends<<endl; } while (cursum> sum && start < mid) { cursum-=start; start++; if (cursum = = sum) { cout<<start<< "-" <<ends<<endl; } } ends++; cursum+=ends; } return;}
Microsoft 100 question 51st: And for n consecutive positive sequence