Topic Requirements
Problem Description : A positive integer may be represented as a sum of N (n>=2) consecutive positive integers, such as:
15=1+2+3+4+5
15=4+5+6
15=7+8
Write a program that finds all consecutive positive integer sequences that meet this requirement, based on any positive integer entered.
Sample Input :
Sample Output : 1+2+3+4+5
4+5+6
7+8
Solution Solutions
Test instructions very understood, the first intuition of this problem is triple-cycle violence, the first control sequence starting point, the second control sequence element number, the third output conforms to the sequence of test instructions, but obviously, this is very time-consuming, can improve? OK!
Because it is a sequential sequence, consider using the arithmetic progression property.
For a linear sequence, there are three key variables: one is tolerance, one is the starting point of the sequence, and the other is the sequence length. Obviously this sequence tolerance is 1, then only the sequence start and sequence length nare considered. Aftertaste arithmetic progression summation formula:
The following information can be obtained from the above formula:
1. The upper type is slightly deformed, 2s-(n-1) N=2a*n, namely 2s> (n-1) n>0.
2. Also 2s= (2a+n-1) n, therefore: 2s%n==0, (2s/n-n+1)%2==0.
3.a= (2s/n-n+1)/2
Therefore, we can consider the method of controlling the length of the sequence to directly find a sequence starting point conforming to test instructions, and then output.
Source code Example
results show
Summary
Although the topic is simple, but still need to consider, do not get a triple loop ...
A positive integer is represented as the sum of n consecutive positive integers (1th session 2nd)